Insert Node from Front in C++

Prev Tutorial Next Tutorial

Linked List Insert Node from Front in C++

insert node in front in c++


node *head = NULL;   //empty linked list

Then we take the data input from the user and store in the node info variable. Create a temporary node node *temp and allocate space for it.


node *temp;             //create a temporary node 
temp = (node*)malloc(sizeof(node)); //allocate space for node

Then place info to temp->data. So the first field of the node *temp is filled. Now temp->next must become a part of the remaining linked list (although now linked list is empty but imagine that we have a 2 node linked list and head is pointed at the front) So temp->next must copy the address of the *head (Because we want insert at first) and we also want that *head will always point at front. So *head must copy the address of the node *temp.


temp->data = info;   // store data(first field)
temp->next=head;   // store the address of the pointer head(second field)
head = temp;

Prev Tutorial Next Tutorial

Google Advertisements
Download Projects

Google Adsense Advertisements

Buy 3 Year Old Domain,, @$200

Buy This Ad Space @$50 per Month, Ad Size 300X250 Contact on: WhatsApp no. 8882538826

Yahoo Advertisements