Skip to main content

Posts

Showing posts with the label Insert node into linked list

Insert a node into sorted list

A singly linked list is a data structure where each node is linked to the next node. In such a list, if you have to add a new node, it can be done in a simple way such as     find the last node     link last node to new node Which can be done using code such as NODEPTR insertnode(NODEPTR head, NODEPTR newnode) { if(head==NULL) { head = newnode; } else { NODEPTR temp = head; while(temp->next !=NULL)//till we have not reached last node { temp = temp->next; } // now temp is our last node. add new node after this temp->next = newnode; } But if we have a sorted list and we want to add a new node to this list we should traverse to first node temp which is greater than new node add the new node to previous node of this prev->next = newnode; newnode->next = temp; To find previous node, each time store current node in prev before moving to next node We also need ...