C program to implement Queue using linked list.

Posted by Mangesh on August 17, 2018

program in c to implement queue using linked list.

Description :

Queue is a container that is use to store objects. It use principle of First In First Out. A queue is a data structure where we add elements at the back and remove elements from the front. In that way a queue is like “waiting in line”: the first one to be added to the queue will be the first one to be removed from the queue. This is also called a FIFO (First In First Out) data structure. Queues are common in many applications. Common example are buffers for network communication that temporarily store packets of data arriving on a network port.

Program :

#include<stdio.h>
#include<conio.h>
typedef struct node
{
  int data;
  struct node *next;
} node;

int empty(node *list)
{
  if(list == NULL)
    return 1;
  return 0;
}


void display(node *list)
{ if(empty(list))
  {
    printf("\n\tQueue is empty, cannot display queue.\n");
  }
  else
  {
    printf("\n\tElements in linked list : ");
    while(list != NULL)
    {
    printf("  %d",list->data);
    list = list->next;
    }
    printf("\n");
  }
}
void main()
{
  node *front, *rear, *newnode;
  int choice=1,data;
  front = NULL;
  rear = NULL;

  clrscr();
  while(choice<=3)
  {
    printf("\n1.insert.  2.delete.  3.display");
    printf("\nEnter your chioce : ");
    scanf("%d",&choice);
    switch(choice)
    {
      case 1:
	printf("\n\tEnter the data for new node : ");
	scanf("%d",&data);
	newnode =  (node *)malloc(sizeof(node));
	newnode->data = data;
	newnode->next = NULL;
	if(empty(front))
	{
	  front = newnode;
	  rear = newnode;
	}else{
	  rear->next = newnode;
	  rear = newnode;
	}
	printf("\tElement inserted in queue.\n");
      break;
      case 2:
	if(empty(front))
	{
	  printf("\n\tQueue is already empty!!!\n");
	}
	else
	{
	  front  = front->next;
	  if(empty(front))
	    printf("\n\tQueue is empty now!!!\n");
	  else
	    printf("\n\tElement deleted\n");
	}

      break;
      case 3:
	display(front);
      break;
    }
  }
getch();
}

Output :

c program for executed and tested in turbo c++ 3.2

Written with from Mangesh.

Related Post
1 C program to create queue using array.
2 C program to implement Queue using linked list.
Latest Post
1 C program to implement Queue using linked list.
2 C program for binary search tree (BST).
3 C program to search an element in linked list.
4 C program for postorder traversal in binary tree.
5 C program for preorder traversal in binary tree.