Linked list Implementation with a return type of node*


#include <iostream>
#include <algorithm>
#include <cstdlib>

using namespace std;

typedef struct node{
int data;
node *next;
};

node *allocate(){
node *ptr = (node *)malloc(sizeof(node));
ptr -> next = NULL;
return ptr;
}

node *f(){
int x;
cin >> x;
if(x == -1)
return NULL;
node *head = allocate();
head ->data = x;
head ->next = f(); //Point the next pointer to the next node
//whose address is returned recursively.
return head; //return the pointer to the current node
}

int main()
{
cout << "Enter items of list:-\nType -1 to exit.\n";
node *head;
head = NULL;
head = f();
while(head!= NULL)
cout << head->data << " ", head = head->next;
return 0;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s