C Program to implement Circular Linked List to insert and delete a node from front and display the contents of the Circular List
Program
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
struct node
{
int info;
struct node *link;
};
typedef struct node* NODE;
NODE getnode()
{
NODE x;
x = (NODE) malloc(sizeof(struct node));
if(x == NULL)
{
printf("Cannot create node\n");
return NULL;
}
return x;
}
void freenode(NODE x)
{
free(x);
}
NODE insert_front(int item, NODE last)
{
NODE temp;
temp = getnode();
temp->info = item;
if(last == NULL)
{
last = temp;
last->link = last;
return last;
}
else
temp->link = last->link;
last->link = temp;
return last;
}
NODE delete_front(NODE last)
{
NODE first;
if(last == NULL)
{
printf("List is empty. Deletion not possible\n");
return NULL;
}
if(last->link == last)
{
printf("The item deleted is %d\n", last->info);
freenode(last);
return NULL;
}
first = last->link;
printf("Item deleted is %d\n", first->info);
last->link = first->link;
freenode(first);
return last;
}
void display(NODE last)
{
NODE cur;
if(last == NULL)
{
printf("List is empty. Cannot print\n");
return;
}
if(last->link == last)
{
printf("%d\n", last->info);
return;
}
cur = last;
while(cur->link != last )
{
cur = cur->link;
printf("%d\n", cur->info);
}
cur = cur->link;
printf("%d\n", cur->info);
}
void main()
{
int choice, item;
NODE last;
last = NULL;
printf("Circular Linked List\n");
printf("Insert and Delete to the front of the list\n");
for(;;)
{
printf("1. Insert Front\n2. Delete Front\n3. Display\n4. Exit\n");
printf("Choice:\t");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("Enter the item to be inserted:\t");
scanf("%d", &item);
last = insert_front(item, last);
break;
case 2:
last = delete_front(last);
break;
case 3:
display(last);
break;
default:
exit(0);
}
}
}
Output
Circular Linked List
Insert and Delete to the front of the list
1. Insert Front
2. Delete Front
3. Display
4. Exit
Choice: 2
List is empty. Deletion not possible
1. Insert Front
2. Delete Front
3. Display
4. Exit
Choice: 1
Enter the item to be inserted: 1
1. Insert Front
2. Delete Front
3. Display
4. Exit
Choice: 1
Enter the item to be inserted: 21
1. Insert Front
2. Delete Front
3. Display
4. Exit
Choice: 1
Enter the item to be inserted: 3
1. Insert Front
2. Delete Front
3. Display
4. Exit
Choice: 3
3
21
1
1. Insert Front
2. Delete Front
3. Display
4. Exit
Choice: 1
Enter the item to be inserted: 20
1. Insert Front
2. Delete Front
3. Display
4. Exit
Choice: 1
Enter the item to be inserted: 17
1. Insert Front
2. Delete Front
3. Display
4. Exit
Choice: 3
17
20
3
21
1
1. Insert Front
2. Delete Front
3. Display
4. Exit
Choice: 2
Item deleted is 17
1. Insert Front
2. Delete Front
3. Display
4. Exit
Choice: 3
20
3
21
1
1. Insert Front
2. Delete Front
3. Display
4. Exit
Choice: 2
Item deleted is 20
1. Insert Front
2. Delete Front
3. Display
4. Exit
Choice: 3
3
21
1
1. Insert Front
2. Delete Front
3. Display
4. Exit
Choice: 4