A simple linked list implementation with no return type and no global pointers.


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

using namespace std;

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

node * alloc(){ //allocate and return the new allocated memory of type node
node *ptr = (node*)malloc(sizeof(node));
ptr -> next = NULL;
ptr -> data = 0;
}

void f(node **head){
int x;
cin >> x;
if(x == -1) //no more data
return ;
*head = alloc(); //allocate new memory
(*head)->data = x;
f(&((*head)->next)); //pass the next pointer of current node to be used recursively.
}

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

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