Sunday, 19 March 2017

C Program to create a Circular Singly Linked List

In circular singly linked list, the last node of the linked list points to the first node of the linked list that's why it is called circular linked list. In circular linked list we use two pointer head & last, head pointer contain the address of the head node and last pointer contains the address of the last node and last->next points to the head of the Linked list. Circular singly linked list has certain advantage over simple singly linked list and that is during the insertion of a node at the end of linked list you don't have to traverse the complete linked list.

Insertion at the beginning and end of Linked List can be done in constant time... 0(1).



Algorithm to create a circular singly linked list

  If  head=NULL:
               1.  create an empty temp node
               2.  set:  temp.data=value
               3.  set.  head=temp
               4.  set:  head.next=head
               5.  set:  last=head
  Else:
               1.  create an empty temp node
               2.  set:  temp.data=value
               3.  set:  temp.next=head
               4.  set:  last.next=temp
               5.  set:  last=temp

C Program to create a circular singly linked list:

       
#include <stdio.h>
#include <stdlib.h>
void insert(int element);
void print();
struct node
{
    int data;
    struct node *next;
}*head=NULL,*temp,*last=NULL;
int main()
{
     int value,ch;
     do
     {
       printf("\nEnter the element you want to insert: ");
       scanf("%d",&value);
       insert(value);
       printf("\nDo you want to continue[1/0]: ");
       scanf("%d",&ch);
     }while(ch==1);
     print();
     printf("\n");
     return 0;
}
void insert(int value)
{
   if(head==NULL)
   {
        temp=(struct node*)malloc(sizeof(struct node));
        temp->data=value;
        head=temp;
        head->next=head;
        last=head;
   }
   else
   {
        temp->next=(struct node*)malloc(sizeof(struct node));
        temp=temp->next;
        temp->data=value;
        temp->next=head;
        last->next=temp;
        last=temp;
   }
}
void print()
{
   struct node *current;
   current=last->next;
   printf("\n");
   do
   {
        printf("%d->",current->data);
        current=current->next;
   }while(current!=last->next);

}

OUTPUT:


See also: C Program to insert a node at the beginning or end in a Circular Singly Linked List
See also: C Program for deleting a node at the beginning or end in  a Circular Singly Linked List


EmoticonEmoticon