#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;
}
Like this:
Like Loading...
Related