Circular Linked List

Sometimes it is necessary for an application the linked list structure is circular. I.e. each node will have a pointer to the next node in the list, but the last element of the list shall point to the first element of the list instead of pointing the null. The coupling between each and every element of the list becomes cyclic. It allows cyclic traversal in the list i.e. going to the first element from the last element and vice versa.

#include<stdio.h>
struct cir
{
int info;
struct cir *next;
};
typedef struct cir node;
node *first,*newl,*prev,*list,*temp,*cur,*p;
int ele;
void create()
{
printf("Type -999 to stop");
scanf("%d",&ele);
while(ele!=-999)
{
newl=(node *)malloc(sizeof(node));
newl->info=ele;
if(first==NULL)
{
newl->next=newl;
first=newl;
}
else
{
newl->next=first->next;
first->next=newl;
}
printf("\nEnter element");
scanf("%d",&ele);
}
}
void count()
{
int c=0;
temp=first;
first=first->next;
while(first!=temp)
{
++c;
first=first->next;
}
++c;
printf("\nNo.of nodes in Circular linked list= %d",c);
}
void print()
{
node *start;
temp=first;
start=first->next;
printf("The Circular linked list is:");
while(start!=temp)
{
printf("%d->",start->info);
start=start->next;


}
printf("%d",start->info);
}
void main()
{
int ch,key;
clrscr();
first=NULL;
do
{
printf("\n1->Creation");
printf("\n2->Print");
printf("\n3->Count");
printf("\n4->Exit");
printf("\nEnter the choice");
scanf("%d",&ch);
switch(ch)
{
case 1:create();break;
case 2:print();break;
case 3:count();break;
case 4:exit(0);break;
default: printf("Invalid Choice");
}
}while(ch!=4);
getch();
}

No comments:

Post a Comment