CLL

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

\\ C program to implement circular linked list

#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
} *head=NULL;
void insert_at_beg()
{
struct node *new_node,*ptr;
int val;
new_node = (struct node*)malloc(sizeof(struct node));
printf("\nEnter value of a node");
scanf("%d",&val);
new_node->data = val;
new_node->next = NULL;
if(head==NULL)
{
head=new_node;
new_node->next=head;
}
else
{
ptr=head;
while(ptr->next!=head)
{
ptr=ptr->next;
}
new_node->next=head;
head = new_node;
ptr->next=head;
}
}

void insert_at_end()
{
struct node *new_node,*ptr;
int val;
new_node = (struct node*) malloc(sizeof(struct node));
printf("\nEnter value of a node");
scanf("%d",&val);
new_node->data = val;
new_node->next = NULL;
if(head==NULL)
{
head=new_node;
new_node->next=head;
}
else
{
ptr=head;
while(ptr->next!=head)
{
ptr=ptr->next;
}
ptr->next = new_node;
new_node->next=head;
}
}
void delete_at_beg()
{
struct node *ptr,*temp;
if(head == NULL)
{
printf("Underflow"); //CLL having no node
}
else if (head->next==head)
{
ptr=head;
head = NULL; //CLL having single node only
free(ptr);
}
else
{
temp=ptr=head;
while(ptr->next!=head)
{ ptr=ptr->next; }

ptr->next=head->next;
head=head->next;
free(temp);
}
}

void delete_at_end()
{
struct node *preptr,*ptr;
if(head == NULL)
{
printf("Underflow");
}
else if (head->next==head)
{
ptr=head;
head = NULL;
free(ptr);
}
else
{
preptr=ptr=head;
while(ptr->next!=head)
{ preptr=ptr;ptr=ptr->next; }
preptr->next=head;
free(ptr);
}
}
void display()
{
struct node *ptr ;
printf("\nElements in linked list are : ");
ptr=head;
do
{
printf("%d--->",ptr->data);
ptr=ptr->next;
} while(ptr!=head);
printf("NULL\n");
}

int main()
{
int x;
while(1)
{
printf("1. insert_beg 2. insert_end 3.delete_beg 4.delete_end 5.traverse 6.exit ");
scanf("%d",&x);
switch(x)
{
case 1: insert_at_beg();
break;
case 2: insert_at_end();
break;
case 3: delete_at_beg();
break;
case 4: delete_at_end();
break;
case 5: display();
break;
case 6: exit(0);
}
} //end of while loop
return 0;
}

You might also like