[click to read Insert at beginning]……………..[click to read Insert between first and last node]
Lets understand each statement
node *temp=new node;
we have a new node and we are interested to insert this node at end of the linked list. temp is a pointer of node-type and will store the address of new node.
temp->info=val;
info is data field of the node, in the information field you assign the value which is passed to a function as an argument.
temp->next=NULL;
next is address field of the node, we set it to NULL because we are sure that this node is going to be the last node of the list (i.e. it will not contain the address of any other node)
if(head==NULL) { head=temp; }
If head equals to NULL, this means we have an empty list and there is no node existing so far in linked list. It also means that this new node is going to be the first node, so will use the same logic that we have discussed in the previous section for an empty list. we will assign the address of stored in temp to head so that head is now pointing to this new node and is the only node in the list.
else { Node *cur =new Node(); ……. …….. ……… }
Otherwise, if there is already a list existing, let’s say our list is as follows
head points to the first node and now we have a new node which is to be added as last node.
We need to start from the first node and keep moving to next node until we reach to the last node. To reach to last node from first node, declare one temporary pointer to traverse the list
Node *cur =new Node();
cur is a pointer of node-type, the logic of this to keep track the address of current node while traversing the list.
cur=head;
now cur is also holding the first node address, means at this point of time head & cur both holds first node address.
while(cur->next!=NULL) { cur=cur->next; }
the purpose of the cur is to keep on moving from one node to another until it reach to last node. So we keep assign the next node address (i.e. cur=cur->next) until the cur->next becomes NULL.
cur->next=temp;
We need to move from node to node in order to reach to the last node, after reaching to last node then in the last node address field we need to put the address of the new node so that we can add the new node at last.

