Insert Node from Front in C++
Linked List Insert Node from 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;