Circular Linked List with Header Node: Delete from Front
#include<stdio.h>
#include<stdlib.h>
struct
node
{
int
data;
struct
node *link;
};
typedef
struct node* NODE;
int count = 0; /* To count no of nodes in the list and put it into
header node */
NODE
getnode()
{
NODE
x;
x
= (NODE)malloc(sizeof(struct node));
return
x;
}
NODE
insert_at_front(NODE head, int item)
{
NODE
temp;
temp
= getnode();
temp->data
= item;
temp->link
= head->link;
head->link
= temp;
head->data
= ++count;
return
head;
}
NODE
delete_at_front(NODE head)
{
NODE
cur;
if(head->link
== head)
{
printf("\nCLL
is empty.");
return
head;
}
cur
= head->link;
head->link
= cur->link;
printf("\nNode
with item %d is deleted", cur->data);
free(cur);
head->data
= --count;
return
head;
}
void
display(NODE head)
{
NODE
temp;
if(head->link
== head)
{
printf("\nList
is empty.");
return;
}
printf("\nContents
of the CLL:\n");
printf("\nNo of nodes in the
CLL is %d\n", head->data);
temp
= head->link;
while(temp!=head)
{
printf("|%d|%d|
--> ",temp->data, temp->link);
temp
= temp->link;
}
}
void
main()
{
int
ch, item;
NODE
head;
head
= getnode();
head->data = 0;
head->link
= head; /*Empty header node*/
while(1)
{
printf("\n~~MENU~~");
printf("\n1:Insert
at Front \n2.Delete at Front \n3:Display \n4:Exit \n");
printf("Enter
the choice: ");
scanf("%d",&ch);
switch(ch)
{
case
1: printf("\nEnter the item to be inserted : ");
scanf("%d", &item);
head
= insert_at_front(head, item);
break;
case
2: head = delete_at_front(head);
break;
case
3: display(head);
break;
case
4: exit(0);
}
}
}
Output:
~~MENU~~
1:Insert
at Front
2.Delete
at Front
3:Display
4:Exit
Enter
the choice: 1
Enter the item to be inserted : 11
~~MENU~~
1:Insert
at Front
2.Delete
at Front
3:Display
4:Exit
Enter
the choice: 1
Enter the item to be inserted : 12
~~MENU~~
1:Insert
at Front
2.Delete
at Front
3:Display
4:Exit
Enter
the choice: 1
Enter the item to be inserted : 14
~~MENU~~
1:Insert
at Front
2.Delete
at Front
3:Display
4:Exit
Enter
the choice: 3
Contents of the CLL:
No of nodes in the CLL is 3
|14|7615608| --> |12|7608072| -->
|11|7608176| -->
~~MENU~~
1:Insert
at Front
2.Delete
at Front
3:Display
4:Exit
Enter
the choice: 2
Node with item 14 is deleted
~~MENU~~
1:Insert
at Front
2.Delete
at Front
3:Display
4:Exit
Enter
the choice: 3
Contents of the CLL:
No of nodes in the CLL is 2
|12|7608072| --> |11|7608176| -->
~~MENU~~
1:Insert
at Front
2.Delete
at Front
3:Display
4:Exit
Enter
the choice: 4