Can someone explain the 'while part' of the code?
The while() part (also described in section 2.) below.) is to look for the node which points to the current head node so that the new node can be inserted just before it. While in the loop, notice that as nodes are found, and they are not yet the head node, they are incremented so as to prepare for the insertion when head node is finally located.
The last expression in the routine:
*head_ref = ptr1;
Is to handle the case described by section 1.) in the general steps below.
General approach for the following initial conditions:
- Linked List is empty:
a) since new_node is the only node in CLL, make a self loop.
new_node->next = new_node;
b) change the head pointer to point to new node.
*head_ref = new_node;
- New node is to be inserted just before the head node:
(a) Find out the last node using a loop.
while(current->next != *head_ref)
current = current->next;
(b) Change the next of last node.
current->next = new_node;
(c) Change next of new node to point to head.
new_node->next = *head_ref;
(d) change the head pointer to point to new node.
*head_ref = new_node;
- New node is to be inserted somewhere after the head:
(a) Locate the node after which new node is to be inserted.
while ( current->next!= *head_ref &&
current->next->data data)
{ current = current->next; }
(b) Make next of new_node as next of the located pointer
new_node->next = current->next;
(c) Change the next of the located pointer
current->next = new_node;
Details and implementation for doing this are shown in this example code
->prevpointer in a doubly-linked list) requires that after adding the new 1st node, you have to traverse the entire list to find the last node and update the->nextpointer so it points to the new 1st node. (lesson: always keep atailpointer or make the list adoubly-linkedlist to preserve O(1) insertions)