C Program to implement Linear Queue using Singly Linked 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 enqueue(NODE , int);
NODE dequeue(NODE);
void display(NODE);
void main()
{
NODE front;
int choice, item;
front = NULL;
while(1)
{
printf("Enter\n");
printf("1. Enqueue\n");
printf("2. Dequeue\n");
printf("3. Display\n");
printf("4. Exit\n");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("Enter item to be inserted\n");
scanf("%d", &item);
front = enqueue(front, item);
break;
case 2:
front = dequeue(front);
break;
case 3:
display(front);
break;
default:
exit(0);
}
}
}
NODE getnode()
{
NODE x;
x = (NODE) malloc(sizeof(struct node));
if(x == NULL)
{
printf("Node creation error\n");
return;
}
return x;
}
NODE enqueue(NODE front , int item)
{
NODE temp, current;
temp = getnode();
temp->info = item;
temp->link = NULL;
if(front == NULL)
{
return temp;
}
current = front;
while(current->link != NULL)
{
current = current->link;
}
current->link = temp;
return front;
}
NODE dequeue(NODE front)
{
NODE temp;
if(front == NULL)
{
printf("Cannot delete. Empty List\n");
return front;
}
temp = front;
front = front->link;
printf("Deleted node is %d\n", temp->info);
free(temp);
return front;
}
void display(NODE front)
{
NODE temp;
if(front == NULL)
{
printf("Cannot print. Empty list\n");
return;
}
temp = front;
printf("Contents of queue is:\n");
while(temp != NULL)
{
printf("%d\n", temp->info);
temp = temp->link;
}
printf("\n");
}
Output
Enter
1. Enqueue
2. Dequeue
3. Display
4. Exit
3
Cannot print. Empty list
Enter
1. Enqueue
2. Dequeue
3. Display
4. Exit
1
Enter item to be inserted
21
Enter
1. Enqueue
2. Dequeue
3. Display
4. Exit
1
Enter item to be inserted
31
Enter
1. Enqueue
2. Dequeue
3. Display
4. Exit
1
Enter item to be inserted
41
Enter
1. Enqueue
2. Dequeue
3. Display
4. Exit
3
Contents of queue is:
21
31
41
Enter
1. Enqueue
2. Dequeue
3. Display
4. Exit
2
Deleted node is 21
Enter
1. Enqueue
2. Dequeue
3. Display
4. Exit
1
Enter item to be inserted
51
Enter
1. Enqueue
2. Dequeue
3. Display
4. Exit
2
Deleted node is 31
Enter
1. Enqueue
2. Dequeue
3. Display
4. Exit
1
Enter item to be inserted
11
Enter
1. Enqueue
2. Dequeue
3. Display
4. Exit
1
Enter item to be inserted
30
Enter
1. Enqueue
2. Dequeue
3. Display
4. Exit
3
Contents of queue is:
41
51
11
30
Enter
1. Enqueue
2. Dequeue
3. Display
4. Exit
2
Deleted node is 41
Enter
1. Enqueue
2. Dequeue
3. Display
4. Exit
4