A queue is a linear data structure that serves as a collection of elements, with three main operations: enqueue, dequeue and peek. We have discussed these operations in the previous post and covered an array implementation of a queue data structure. In this post, the linked list implementation of a queue is discussed.

Practice this problem

A queue can be easily implemented using a linked list. In singly linked list implementation, enqueuing happens at the tail of the list, and the dequeuing of items happens at the head of the list. We need to maintain a pointer to the last node to keep O(1) efficiency for insertion.

Since a doubly linked list offers O(1) insertion and deletion at both ends, use it if we want to enqueue to happen at the beginning and dequeuing to occur at the tail of the linked list.

 
Following is the implementation of the queue using a linked list in C, Java, and Python:

C


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
Inserting 1
Inserting 2
Inserting 3
Inserting 4
The front element is 1
Removing 1
Removing 2
Removing 3
Removing 4
The queue is empty

The advantage of using linked lists over arrays is that it is possible to implement a queue that can grow or shrink as much as needed. Since each new node will be dynamically allocated, overflow is not possible unless heap memory is exhausted. Using a static array will restrict the array’s maximum capacity, which can lead to queue overflow.