Circular linked list C program
Circular linked list C program, circular linked list program in c, circular linked list c++, circular linked list algorithm, circular linked list in c program, circular link list program in c, circular link list in c, c program to implement circular linked list, circular linked list c++ code
Circular linked list C program
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
} *head=NULL , *tail=NULL;
void AddElement();
void DeleteElement();
void Display();
int main()
{
printf("Program to Implement Circular Linked List\n");
int ch;
while(1)
{
printf("\n\n1] Insert An Element");
printf("\n2] Delete An Element");
printf("\n3] Display List");
printf("\n4] Exit");
printf("\n Your choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1:
AddElement();
Display();
break;
case 2:
DeleteElement();
Display();
break;
case 3:
Display();
break;
case 4:
return(0);
}
}
}
void AddElement()
{
int element;
struct node *ptr,*prev,*temp;
temp=(struct node*)malloc(sizeof(struct node));
printf("\nEnter the new element : ");
scanf("%d",&element);
temp->data=element;
temp->next=NULL;
if (head==NULL)
{
head=tail=temp;
temp->next=head;
}
else
{
tail->next=temp;
tail=temp;
}
}
void DeleteElement()
{
struct node *ptr,*prev,*delnode;
int key;
Display();
printf("\nEnter the Element which you want to delete : ");
scanf("%d",&key);
if(head==NULL)
{
printf("\nNo elements in the list \n");
return;
}
else
{
if(head->data==key)
{
delnode=head;
if (head==tail)
head=tail=NULL;
else
{
head=head->next;
tail->next=head;
}
}
else if (tail->data==key)
{
for(ptr=head;(ptr!=tail);prev=ptr,ptr=ptr->next);
delnode=tail;
tail=prev;
tail->next=head;
}
else
{
for(prev=ptr=head;(ptr->data!=key)&&(ptr!=tail);
prev=ptr,ptr=ptr->next);
if(ptr->data==key)
{
delnode=ptr;
prev->next=ptr->next;
printf("\nElement Deleted");
}
else
{
printf("\nGiven element not found in the list");
return;
}
}
}
free(delnode);
}
void Display()
{
int count=0;
struct node *ptr,*prev=NULL;
if (head==NULL)
{
printf("\nThe list is empty\n");
return;
}
printf("\nThe elements in the circular list are\n");
for (ptr=head;prev!=tail;prev=ptr,ptr=ptr->next)
{
count++;
printf("%d ",ptr->data);
}
printf("\nTotal number of element(s) in the list are : %d\n",count);
}
No comments:
Write comments