Dynamic Circular Linked Lists in C

Circular lists eliminates same drawbacks of linear lists. In as circular list it is assumed that items are inserted at the front and the list pointer points to the currently inserted node. Now, in this currently inserted circular list items, node or item is the last node of the list (and is this the rear node) and the first node or the front of the list is the node pointed to by the next pointer of last node. Thus, the next pointer of last node always points to the first front node.

Dynamic-Circular-Linked-List

 

Such an implementation of a circular list is almost similar to a circular queue. The insert and delete functions of a circular list are similar to that of a linear list but with some modifications. In the insert function, modification is made so that the next pointer of rear node always points to the front node. In the delete function, modification is made so that the function returns without deleting the very last node. See below how a dynamic circular linked list can be implemented in C –

void insert (NODEPTR *p, intx){
     NODEPTR q;
     q = getnode();
     q->info = x;
     if(*p == NULL){
         *p = q;
     }
     else{
         q->next = (*p)->next;
     }
     (*p)->next = q;
     *p = q; /*implements circular pointer operation*/
      return;     
}

void delafter(NODEPTR *p, int x){
      NODEPTR q;
      /*if list is NULL or has any item*/
      if((p == NULL) || (p == p->next)){
         printf("\n Void Deletion");
         return;
      }
      q = (*p)->next;
      *x = p->info;
      (*p)->next = q->next;
      freenode(q);
}

 

Add a Comment

Your email address will not be published. Required fields are marked *