Reputation: 70
Can someone explain the 'while part' of the code?- in the main() head is declared as struct node pointer initialized with value NULL. and a node is inserted by calling function = push(&head,12)
void push(struct Node **head_ref, int data)
{
struct Node *ptr1 = (struct Node *)malloc(sizeof(struct Node));
struct Node *temp = *head_ref;
ptr1->data = data;
ptr1->next = *head_ref;
if (*head_ref != NULL)
{
while (temp->next != *head_ref)
temp = temp->next;
temp->next = ptr1;
}
else
ptr1->next = ptr1; /*For the first node */
*head_ref = ptr1;
}
Upvotes: 1
Views: 372
Reputation: 23218
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:
Details and implementation for doing this are shown in this example code
Upvotes: 2