Need a project done?

C++ Programming Developer

Search This Blog

Printing Linked List in Reverse Order Recursively in C++


Printing Linked List in Reverse Order Recursively in C++ Program is given below:

// Printing Linked List in Reverse Order Recursively in C++
// Insertion at head is done in the following program
#include <iostream>
using namespace std;

////////////////////////////////////////////////////////////////
struct link                           //one element of list
{
int data;                          //data item
link* next;                        //pointer to next link
};
////////////////////////////////////////////////////////////////
class linklist                        //a list of links
{
private:
link* first;                    //pointer to first link also known as head.
public:
linklist()                      //no-argument constructor
{ first = NULL; }            //no first link
link* getHead(){ return first; }
void additem(int d);            //add data item (one link)
void displayRecursivelyReversed(link* current);                 //display all links in REVERSE ORDER.
};
//-------------------------------------------------------------void
void linklist::additem(int d)         //add data item
{
link *newLink = new link;
newLink->data = d;
//insert at head
newLink->next = first;
first = newLink;
}
//-------------------------------------------------------------void
void linklist::displayRecursivelyReversed(link* current)              //display all links
{
if (current != NULL){
//move to next node.
displayRecursively(current->next);
cout << current->data << endl;
}

}
////////////////////////////////////////////////////////////////
int main()
{
linklist li;       //make linked list
li.additem(25);    //add four items to list
li.additem(36);
li.additem(49);
li.additem(64);
li.displayRecursivelyReversed(li.getHead());      //display entire list
return 0;
}

No comments:

Post a Comment

"Don't let anyone ever make you feel like you don't deserve what you want."