Queue - Linked List Implementation - GeeksforGeeks

06 Aug, 2021
In the previous post, we introduced Queue and discussed array implementation. In this post, linked list implementation is discussed. The following two main operations must be implemented efficiently.In a Queue data structure, we maintain two pointers, front and rear. The front points the first item of queue and rear points to last item.enQueue() This operation adds a new node after rear and moves rear to the next node.deQueue() This operation removes the front node and moves front to the next node. 
 
C++
C
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std; struct QNode {    int data;    QNode* next;    QNode(int d)    {        data = d;        next = NULL;    }}; struct Queue {    QNode *front, *rear;    Queue()    {        front = rear = NULL;    }     void enQueue(int x)    {         // Create a new LL node        QNode* temp = new QNode(x);         // If queue is empty, then        // new node is front and rear both        if (rear == NULL) {            front = rear = temp;            return;        }         // Add the new node at        // the end of queue and change rear        rear->next = temp;        rear = temp;    }     // Function to remove    // a key from given queue q    void deQueue()    {        // If queue is empty, return NULL.        if (front == NULL)            return;         // Store previous front and        // move front one node ahead        QNode* temp = front;        front = front->next;         // If front becomes NULL, then        // change rear also as NULL        if (front == NULL)            rear = NULL;         delete (temp);    }}; // Driven Programint main(){     Queue q;    q.enQueue(10);    q.enQueue(20);    q.deQueue();    q.deQueue();    q.enQueue(30);    q.enQueue(40);    q.enQueue(50);    q.deQueue();    cout << "Queue Front : " << (q.front)->data << endl;    cout << "Queue Rear : " << (q.rear)->data;}// This code is contributed by rathbhupendra
// A C program to demonstrate linked list based implementation of queue#include <stdio.h>#include <stdlib.h> // A linked list (LL) node to store a queue entrystruct QNode {    int key;    struct QNode* next;}; // The queue, front stores the front node of LL and rear stores the// last node of LLstruct Queue {    struct QNode *front, *rear;}; // A utility function to create a new linked list node.struct QNode* newNode(int k){    struct QNode* temp = (struct QNode*)malloc(sizeof(struct QNode));    temp->key = k;    temp->next = NULL;    return temp;} // A utility function to create an empty queuestruct Queue* createQueue(){    struct Queue* q = (struct Queue*)malloc(sizeof(struct Queue));    q->front = q->rear = NULL;    return q;} // The function to add a key k to qvoid enQueue(struct Queue* q, int k){    // Create a new LL node    struct QNode* temp = newNode(k);     // If queue is empty, then new node is front and rear both    if (q->rear == NULL) {        q->front = q->rear = temp;        return;    }     // Add the new node at the end of queue and change rear    q->rear->next = temp;    q->rear = temp;} // Function to remove a key from given queue qvoid deQueue(struct Queue* q){    // If queue is empty, return NULL.    if (q->front == NULL)        return;     // Store previous front and move front one node ahead    struct QNode* temp = q->front;     q->front = q->front->next;     // If front becomes NULL, then change rear also as NULL    if (q->front == NULL)        q->rear = NULL;     free(temp);} // Driver Program to test anove functionsint main(){    struct Queue* q = createQueue();    enQueue(q, 10);    enQueue(q, 20);    deQueue(q);    deQueue(q);    enQueue(q, 30);    enQueue(q, 40);    enQueue(q, 50);    deQueue(q);    printf("Queue Front : %d \n", q->front->key);    printf("Queue Rear : %d", q->rear->key);    return 0;}
// Java program for linked-list implementation of queue // A linked list (LL) node to store a queue entryclass QNode {    int key;    QNode next;     // constructor to create a new linked list node    public QNode(int key)    {        this.key = key;        this.next = null;    }} // A class to represent a queue// The queue, front stores the front node of LL and rear stores the// last node of LLclass Queue {    QNode front, rear;     public Queue()    {        this.front = this.rear = null;    }     // Method to add an key to the queue.    void enqueue(int key)    {         // Create a new LL node        QNode temp = new QNode(key);         // If queue is empty, then new node is front and rear both        if (this.rear == null) {            this.front = this.rear = temp;            return;        }         // Add the new node at the end of queue and change rear        this.rear.next = temp;        this.rear = temp;    }     // Method to remove an key from queue.    void dequeue()    {        // If queue is empty, return NULL.        if (this.front == null)            return;         // Store previous front and move front one node ahead        QNode temp = this.front;        this.front = this.front.next;         // If front becomes NULL, then change rear also as NULL        if (this.front == null)            this.rear = null;    }} // Driver classpublic class Test {    public static void main(String[] args)    {        Queue q = new Queue();        q.enqueue(10);        q.enqueue(20);        q.dequeue();        q.dequeue();        q.enqueue(30);        q.enqueue(40);        q.enqueue(50);        q.dequeue();        System.out.println("Queue Front : " + q.front.key);        System.out.println("Queue Rear : " + q.rear.key);    }}// This code is contributed by Gaurav Miglani
# Python3 program to demonstrate linked list# based implementation of queue # A linked list (LL) node# to store a queue entryclass Node:         def __init__(self, data):        self.data = data        self.next = None # A class to represent a queue # The queue, front stores the front node# of LL and rear stores the last node of LLclass Queue:         def __init__(self):        self.front = self.rear = None     def isEmpty(self):        return self.front == None         # Method to add an item to the queue    def EnQueue(self, item):        temp = Node(item)                 if self.rear == None:            self.front = self.rear = temp            return        self.rear.next = temp        self.rear = temp     # Method to remove an item from queue    def DeQueue(self):                 if self.isEmpty():            return        temp = self.front        self.front = temp.next         if(self.front == None):            self.rear = None # Driver Codeif __name__== '__main__':    q = Queue()    q.EnQueue(10)    q.EnQueue(20)    q.DeQueue()    q.DeQueue()    q.EnQueue(30)    q.EnQueue(40)    q.EnQueue(50)    q.DeQueue()      print("Queue Front " + str(q.front.data))    print("Queue Rear " + str(q.rear.data))    
// C# program for linked-list// implementation of queueusing System; // A linked list (LL) node to// store a queue entryclass QNode {    public int key;    public QNode next;     // constructor to create    // a new linked list node    public QNode(int key)    {        this.key = key;        this.next = null;    }} // A class to represent a queue The queue,// front stores the front node of LL and// rear stores the last node of LLclass Queue {    QNode front, rear;     public Queue()    {        this.front = this.rear = null;    }     // Method to add an key to the queue.    public void enqueue(int key)    {         // Create a new LL node        QNode temp = new QNode(key);         // If queue is empty, then new        // node is front and rear both        if (this.rear == null) {            this.front = this.rear = temp;            return;        }         // Add the new node at the        // end of queue and change rear        this.rear.next = temp;        this.rear = temp;    }     // Method to remove an key from queue.    public void dequeue()    {        // If queue is empty, return NULL.        if (this.front == null)            return;         // Store previous front and        // move front one node ahead        QNode temp = this.front;        this.front = this.front.next;         // If front becomes NULL,        // then change rear also as NULL        if (this.front == null)            this.rear = null;    }} // Driver codepublic class Test {    public static void Main(String[] args)    {        Queue q = new Queue();        q.enqueue(10);        q.enqueue(20);        q.dequeue();        q.dequeue();        q.enqueue(30);        q.enqueue(40);        q.enqueue(50);        q.dequeue();        Console.WriteLine("Queue Front : " + q.front.key);        Console.WriteLine("Queue Rear : " + q.rear.key);    }} // This code has been contributed by Rajput-Ji
<script>// JavaScript program for linked-list implementation of queueclass QNode{    constructor(key)    {        this.key = key;        this.next = null;    }} let front = null, rear = null; function enqueue(key){    // Create a new LL node        let temp = new QNode(key);           // If queue is empty, then new node is front and rear both        if (rear == null) {            front = rear = temp;            return;        }           // Add the new node at the end of queue and change rear        rear.next = temp;        rear = temp;}  function dequeue(){    // If queue is empty, return NULL.        if (front == null)            return;           // Store previous front and move front one node ahead        let temp = front;        front = front.next;           // If front becomes NULL, then change rear also as NULL        if (front == null)            rear = null;}  enqueue(10);enqueue(20);dequeue();dequeue();enqueue(30);enqueue(40);enqueue(50);dequeue();document.write("Queue Front : " + front.key+"<br>");document.write("Queue Rear : " + rear.key+"<br>");  // This code is contributed by avanitrachhadiya2155</script>
Queue Front : 40
Queue Rear : 50
 
Time Complexity: Time complexity of both operations enqueue() and dequeue() is O(1) as we only change few pointers in both operations. There is no loop in any of the operations.   
YouTubeGeeksforGeeks506K subscribersQueue | Set 2 (Linked List Implementation) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 10:39•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=C6KjYbAarYI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
 Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
Rajput-Ji
rathbhupendra
ManasChhabra2
md1844
ckb2001
cosine1509
avanitrachhadiya2155
Amazon
Oracle
Qualcomm
Samsung
Linked List
Queue
Amazon
Samsung
Oracle
Qualcomm
Linked List
Queue
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Reverse a linked list
LinkedList in Java
Doubly Linked List | Set 1 (Introduction and Insertion)
Detect loop in a linked list
Merge two sorted linked lists
Level Order Binary Tree Traversal
Queue Interface In Java
Queue in Python
Circular Queue | Set 1 (Introduction and Array Implementation)
Sliding Window Maximum (Maximum of all subarrays of size k)