Need a project done?

C++ Programming Developer

Search This Blog

Printing Linked List Recursively in C++

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


// Printing Linked List Recursively in C++
// Linked List is created by inserting at head and then printing recursively.
#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
public:
linklist()                      //no-argument constructor
{ first = NULL; }            //no first link
link* getHead(){ return first; }
void additem(int d);            //add data item (one link)
void displayRecursively(link* current);                 //display all links
};
//-------------------------------------------------------------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::displayRecursively(link* current)              //display all links
{
if (current != NULL){
cout << current->data << endl;  //print data
displayRecursively(current->next);
}
}
////////////////////////////////////////////////////////////////
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.displayRecursively(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."