MridulRao
MridulRao

Reputation: 70

how to insert node in Circular Linked list in C

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

Answers (1)

ryyker
ryyker

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:

  1. 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;
  2. 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;
  3. 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

Upvotes: 2

Related Questions