Queue in C using linked list


Queue is a FIFO mechanism. FIFO means FIRST IN FIRST OUT. It is a normal queue as we see when we go for booking a movie ticket. The person who is standing first gets the ticket first.

Create a node

struct node{
    int data;
    struct node *link;    
    };

Enqueue or add an item in queue

  • Create a node and assign a data to it.
  • Maintain two pointers : Front and Rear.
  • Items will be added to the rear side of the queue.
void addItem(struct node **front, struct node **rear, int data){
    struct node *temp;
     temp = (struct node*) malloc(sizeof(struct node));  
     temp->data = data;
       if(*front == NULL){
           *front = *rear = temp;
           
       }else{
           (*rear)->link = temp;
           *rear =  (*rear)->link;
       }
       
}

Code to display the items of the queue

  1. Traverse through the front part of the queue and keep on displaying the data.
  2. Increment the link.
void display(struct node *temp){
    while(temp!=NULL){
        printf("\n%d\n", temp->data);
        temp = temp->link;
        
    }
}

Code to delete the item from queue

To dequeue just change the front part of the queue.

void dequeue(struct node** front){
    (*front) = (*front) -> link;
    
}

Complete code to enqueue and dequeue.

#include <stdio.h>
#include <string.h>
#include <malloc.h>
struct node{
    int data;
    struct node *link;    
    };
void addItem(struct node**, struct node**, int data);
void display(struct node*);
void dequeue(struct node**);
main()
{
    struct node *front, *rear;
    front = rear = NULL;
    addItem(&front, &rear, 3);
    addItem(&front, &rear, 25);
    addItem(&front, &rear, 1);
    printf("enque");
    display(front);
     printf("Deque");
    dequeue(&front);
    display(front);
      
}
void addItem(struct node **front, struct node **rear, int data){
    struct node *temp;
     temp = (struct node*) malloc(sizeof(struct node));  
     temp->data = data;
       if(*front == NULL){
           *front = *rear = temp;
           
       }else{
           (*rear)->link = temp;
           *rear =  (*rear)->link;
       }
       
}
void display(struct node *temp){
    while(temp!=NULL){
        printf("\n%d\n", temp->data);
        temp = temp->link;
        
    }
}
void dequeue(struct node** front){
    (*front) = (*front) -> link;
    
}

Output :

In this note we studied about queue in c using linked list. In the next note we will add more operations to queue and we will also implement queue using arrays.