The Wayback Machine - https://web.archive.org/web/20240926202551/https://www.geeksforgeeks.org/circular-linked-list-implementation-of-circular-queue/
Open In App

Circular Linked List Implementation of Circular Queue

Last Updated : 22 Feb, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisite – Circular Singly Linked List We have discussed basics and how to implement circular queue using array in set 1. Circular Queue | Set 1 (Introduction and Array Implementation) In this post another method of circular queue implementation is discussed, using Circular Singly Linked List. 

Operations on Circular Queue:

  • Front:Get the front item from queue.
  • Rear: Get the last item from queue.
  • enQueue(value) This function is used to insert an element into the circular queue. In a circular queue, the new element is always inserted at Rear position.
    1. Create a new node dynamically and insert value into it.
    2. Check if front==NULL, if it is true then front = rear = (newly created node)
    3. If it is false then rear=(newly created node) and rear node always contains the address of the front node.
  • deQueue() This function is used to delete an element from the circular queue. In a queue, the element is always deleted from front position.
    1. Check whether queue is empty or not means front == NULL.
    2. If it is empty then display Queue is empty. If queue is not empty then step 3
    3. Check if (front==rear) if it is true then set front = rear = NULL else move the front forward in queue, update address of front in rear node and return the element.

Operations-on-Circular -Queue 

Below is the implementation of the above approach: 

C++




// C++ program for insertion and
// deletion in Circular Queue
#include <bits/stdc++.h>
using namespace std;
 
// Structure of a Node
struct Node {
    int data;
    struct Node* link;
};
 
struct Queue {
    struct Node *front, *rear;
};
 
// Function to create Circular queue
void enQueue(Queue* q, int value)
{
    struct Node* temp = new Node;
    temp->data = value;
    if (q->front == NULL)
        q->front = temp;
    else
        q->rear->link = temp;
 
    q->rear = temp;
    q->rear->link = q->front;
}
 
// Function to delete element from Circular Queue
int deQueue(Queue* q)
{
    if (q->front == NULL) {
        cout << "Queue is empty";
        return INT_MIN;
    }
 
    // If this is the last node to be deleted
    int value; // Value to be dequeued
    if (q->front == q->rear) {
        value = q->front->data;
        free(q->front);
        q->front = NULL;
        q->rear = NULL;
    }
    else // There are more than one nodes
    {
        struct Node* temp = q->front;
        value = temp->data;
        q->front = q->front->link;
        q->rear->link = q->front;
        free(temp);
    }
 
    return value;
}
 
// Function displaying the elements of Circular Queue
void displayQueue(struct Queue* q)
{
    struct Node* temp = q->front;
    cout << endl << "Elements in Circular Queue are: ";
    while (temp->link != q->front) {
        cout << temp->data << " ";
        temp = temp->link;
    }
    cout << temp->data;
}
 
/* Driver of the program */
int main()
{
    // Create a queue and initialize front and rear
    Queue* q = new Queue;
    q->front = q->rear = NULL;
 
    // Inserting elements in Circular Queue
    enQueue(q, 14);
    enQueue(q, 22);
    enQueue(q, 6);
 
    // Display elements present in Circular Queue
    displayQueue(q);
 
    // Deleting elements from Circular Queue
    cout << endl << "Deleted value = " << deQueue(q);
    cout << endl << "Deleted value = " << deQueue(q);
 
    // Remaining elements in Circular Queue
    displayQueue(q);
 
    enQueue(q, 9);
    enQueue(q, 20);
    displayQueue(q);
 
    return 0;
}


Java




// Java program for insertion and
// deletion in Circular Queue
import java.io.*;
import java.util.*;
 
public class Solution {
 
    // Structure of a Node
    static class Node {
        int data;
        Node link;
    }
 
    static class Queue {
        Node front, rear;
    }
 
    // Function to create Circular queue
    static void enQueue(Queue q, int value)
    {
        Node temp = new Node();
        temp.data = value;
        if (q.front == null)
            q.front = temp;
        else
            q.rear.link = temp;
 
        q.rear = temp;
        q.rear.link = q.front;
    }
 
    // Function to delete element from Circular Queue
    static int deQueue(Queue q)
    {
        if (q.front == null) {
            System.out.printf("Queue is empty");
            return Integer.MIN_VALUE;
        }
 
        // If this is the last node to be deleted
        int value; // Value to be dequeued
        if (q.front == q.rear) {
            value = q.front.data;
            q.front = null;
            q.rear = null;
        }
        else // There are more than one nodes
        {
            Node temp = q.front;
            value = temp.data;
            q.front = q.front.link;
            q.rear.link = q.front;
        }
 
        return value;
    }
 
    // Function displaying the elements of Circular Queue
    static void displayQueue(Queue q)
    {
        Node temp = q.front;
        System.out.printf(
            "\nElements in Circular Queue are: ");
        while (temp.link != q.front) {
            System.out.printf("%d ", temp.data);
            temp = temp.link;
        }
        System.out.printf("%d", temp.data);
    }
 
    /* Driver of the program */
    public static void main(String args[])
    {
        // Create a queue and initialize front and rear
        Queue q = new Queue();
        q.front = q.rear = null;
 
        // Inserting elements in Circular Queue
        enQueue(q, 14);
        enQueue(q, 22);
        enQueue(q, 6);
 
        // Display elements present in Circular Queue
        displayQueue(q);
 
        // Deleting elements from Circular Queue
        System.out.printf("\nDeleted value = %d",
                          deQueue(q));
        System.out.printf("\nDeleted value = %d",
                          deQueue(q));
 
        // Remaining elements in Circular Queue
        displayQueue(q);
 
        enQueue(q, 9);
        enQueue(q, 20);
        displayQueue(q);
    }
}
 
// This code is contributed
// by Arnab Kundu


Python3




# Python3 program for insertion and
# deletion in Circular Queue
 
# Structure of a Node
class Node:
    def __init__(self):
        self.data = None
        self.link = None
 
class Queue:
    def __init__(self):
        front = None
        rear = None
 
# Function to create Circular queue
def enQueue(q, value):
    temp = Node()
    temp.data = value
    if (q.front == None):
        q.front = temp
    else:
        q.rear.link = temp
 
    q.rear = temp
    q.rear.link = q.front
 
# Function to delete element from
# Circular Queue
def deQueue(q):
    if (q.front == None):
        print("Queue is empty")
        return -999999999999
 
    # If this is the last node to be deleted
    value = None # Value to be dequeued
    if (q.front == q.rear):
        value = q.front.data
        q.front = None
        q.rear = None
    else: # There are more than one nodes
        temp = q.front
        value = temp.data
        q.front = q.front.link
        q.rear.link = q.front
 
    return value
 
# Function displaying the elements
# of Circular Queue
def displayQueue(q):
    temp = q.front
    print("Elements in Circular Queue are: ",
                                   end = " ")
    while (temp.link != q.front):
        print(temp.data, end = " ")
        temp = temp.link
    print(temp.data)
 
# Driver Code
if __name__ == '__main__':
 
    # Create a queue and initialize
    # front and rear
    q = Queue()
    q.front = q.rear = None
 
    # Inserting elements in Circular Queue
    enQueue(q, 14)
    enQueue(q, 22)
    enQueue(q, 6)
 
    # Display elements present in
    # Circular Queue
    displayQueue(q)
 
    # Deleting elements from Circular Queue
    print("Deleted value = ", deQueue(q))
    print("Deleted value = ", deQueue(q))
 
    # Remaining elements in Circular Queue
    displayQueue(q)
 
    enQueue(q, 9)
    enQueue(q, 20)
    displayQueue(q)
 
# This code is contributed by PranchalK


C#




// C# program for insertion and
// deletion in Circular Queue
using System;
using System.Collections.Generic;
 
public class GFG {
 
    // Structure of a Node
    public class Node {
        public int data;
        public Node link;
    }
 
    public class LinkedList {
        public Node front, rear;
    }
 
    // Function to create Circular queue
    public static void enQueue(LinkedList q,
                               int value)
    {
        Node temp = new Node();
        temp.data = value;
        if (q.front == null) {
            q.front = temp;
        }
        else {
            q.rear.link = temp;
        }
 
        q.rear = temp;
        q.rear.link = q.front;
    }
 
    // Function to delete element from
    // Circular Queue
    public static int deQueue(LinkedList q)
    {
        if (q.front == null) {
            Console.Write("Queue is empty");
            return int.MinValue;
        }
 
        // If this is the last node to be deleted
        int value; // Value to be dequeued
        if (q.front == q.rear) {
            value = q.front.data;
            q.front = null;
            q.rear = null;
        }
        else // There are more than one nodes
        {
            Node temp = q.front;
            value = temp.data;
            q.front = q.front.link;
            q.rear.link = q.front;
        }
 
        return value;
    }
 
    // Function displaying the elements
    // of Circular Queue
    public static void displayQueue(LinkedList q)
    {
        Node temp = q.front;
        Console.Write("\nElements in Circular Queue are: ");
        while (temp.link != q.front) {
            Console.Write("{0:D} ", temp.data);
            temp = temp.link;
        }
        Console.Write("{0:D}", temp.data);
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        // Create a queue and initialize
        // front and rear
        LinkedList q = new LinkedList();
        q.front = q.rear = null;
 
        // Inserting elements in Circular Queue
        enQueue(q, 14);
        enQueue(q, 22);
        enQueue(q, 6);
 
        // Display elements present in
        // Circular Queue
        displayQueue(q);
 
        // Deleting elements from Circular Queue
        Console.Write("\nDeleted value = {0:D}",
                      deQueue(q));
        Console.Write("\nDeleted value = {0:D}",
                      deQueue(q));
 
        // Remaining elements in Circular Queue
        displayQueue(q);
 
        enQueue(q, 9);
        enQueue(q, 20);
        displayQueue(q);
    }
}
 
// This code is contributed by Shrikant13


Javascript




// Javascript program for insertion and deletion in Circular Queue
 
      // Structure of a Node
      class Node {
        constructor() {
          this.data;
          this.node;
        }
      }
 
      class Queue {
        constructor() {
          this.front;
          this.rear;
        }
      }
 
      // Function to create Circular queue
      function enQueue(q, value) {
        temp = new Node();
        temp.data = value;
        if (q.front == null) q.front = temp;
        else q.rear.link = temp;
 
        q.rear = temp;
        q.rear.link = q.front;
      }
 
      // Function to delete element from Circular Queue
      function deQueue(q) {
        if (q.front == null) {
          console.log("Queue is empty");
          return Number.MIN_VALUE;
        }
 
        // If this is the last node to be deleted
        let value; // Value to be dequeued
        if (q.front == q.rear) {
          value = q.front.data;
          q.front = null;
          q.rear = null;
        } // There are more than one nodes
        else {
          temp = q.front;
          value = temp.data;
          q.front = q.front.link;
          q.rear.link = q.front;
        }
 
        return value;
      }
 
      // Function displaying the elements of Circular Queue
      function displayQueue(q) {
        temp = q.front;
        console.log("Elements in Circular Queue are: ");
        while (temp.link != q.front) {
          console.log(temp.data);
          temp = temp.link;
        }
        console.log(temp.data);
      }
 
      /* Driver of the program */
 
      // Create a queue and initialize front and rear
      q = new Queue();
      q.front = q.rear = null;
 
      // Inserting elements in Circular Queue
      enQueue(q, 14);
      enQueue(q, 22);
      enQueue(q, 6);
 
      // Display elements present in Circular Queue
      displayQueue(q);
 
      // Deleting elements from Circular Queue
      console.log("Deleted value = " + deQueue(q));
      console.log("Deleted value = " + deQueue(q));
 
      // Remaining elements in Circular Queue
      displayQueue(q);
 
      enQueue(q, 9);
      enQueue(q, 20);
      displayQueue(q);


Output

Elements in Circular Queue are: 14 22 6
Deleted value = 14
Deleted value = 22
Elements in Circular Queue are: 6
Elements in Circular Queue are: 6 9 20

Time Complexity: Time complexity of enQueue(), deQueue() operation is O(1) as there is no loop in any of the operation. 
Auxiliary Space: O(n) where n is the maximum number of elements that can be stored in the queue.

Note: In case of linked list implementation, a queue can be easily implemented without being circular. However, in the case of array implementation, we need a circular queue to save space. 



Similar Reads

What is Circular Queue | Circular Queue meaning
A circular queue is an extended version of regular queue in which the last element of the queue is connected to the first element of the queue forming a cycle. Properties of Circular Queue: Along with the properties of a regular queue the circular queue has som other unique properties as mentioned below: Front and rear pointers: Two pointers, one a
4 min read
Should we declare as Queue or Priority Queue while using Priority Queue in Java?
Queue: Queue is an Interface that extends the collection Interface in Java and this interface belongs to java.util package. A queue is a type of data structure that follows the FIFO (first-in-first-out ) order. The queue contains ordered elements where insertion and deletion of elements are done at different ends. Priority Queue and Linked List are
3 min read
Queue - Linked List Implementation
In this article, the Linked List implementation of the queue data structure is discussed and implemented. Print '-1' if the queue is empty. Approach: To solve the problem follow the below idea: we maintain two pointers, front, and rear. The front points to the first item of the queue and rear points to the last item. enQueue(): This operation adds
14 min read
Advantages of circular queue over linear queue
Linear Queue: A Linear Queue is generally referred to as Queue. It is a linear data structure that follows the FIFO (First In First Out) order. A real-life example of a queue is any queue of customers waiting to buy a product from a shop where the customer that came first is served first. In Queue all deletions (dequeue) are made at the front and a
3 min read
Difference Between Linear Queue and Circular Queue
Queues are fundamental data structures in computer science that follow the First-In-First-Out (FIFO) principle. Among the various types of queues, linear queues and circular queues are commonly used. While they share some similarities, they differ significantly in structure and operational efficiency. This article explores the concepts, advantages,
4 min read
Difference between Circular Queue and Priority Queue
Queues are fundamental data structures that are used to store and manage a collection of elements. While both circular queues and priority queues are types of queues, they have distinct characteristics and applications. This article will explore the key differences between circular queues and priority queues. Circular Queue:A Circular Queue is an e
4 min read
Check if a linked list is Circular Linked List
Given the head of a singly linked list, the task is to find if given linked list is circular or not. A linked list is called circular if its last node points back to its first node. Note: The linked list does not contain any internal loops. Example: Input: LinkedList: 2->4->6->7->5 Output: trueExplanation: As shown in figure the first a
12 min read
Convert singly linked list into circular linked list
Given a singly linked list, the task is to convert it into a circular linked list. Examples: Input: head: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULLOutput: Explanation: Singly linked list is converted to circular by pointing last node to head. Input: head: 2 -> 4 -> 6 -> 8 -> 10 -> 12 -> NULLOutput: Explanation: Singly l
11 min read
Stack and Queue in Python using queue Module
A simple python List can act as queue and stack as well. Queue mechanism is used widely and for many purposes in daily life. A queue follows FIFO rule(First In First Out) and is used in programming for sorting and for many more things. Python provides Class queue as a module which has to be generally created in languages such as C/C++ and Java. 1.
3 min read
Check if a queue can be sorted into another queue using a stack
Given a Queue consisting of first n natural numbers (in random order). The task is to check whether the given Queue elements can be arranged in increasing order in another Queue using a stack. The operation allowed are: Push and pop elements from the stack Pop (Or Dequeue) from the given Queue. Push (Or Enqueue) in the another Queue. Examples : Inp
9 min read
Reversing a Queue using another Queue
Given a queue. The task is to reverse the queue using another empty queue. Examples: Input: queue[] = {1, 2, 3, 4, 5} Output: 5 4 3 2 1 Input: queue[] = {10, 20, 30, 40} Output: 40 30 20 10 Approach: Given a queue and an empty queue.The last element of the queue should be the first element of the new queue.To get the last element there is a need to
5 min read
Difference between Queue and Deque (Queue vs. Deque)
Queue: The queue is an abstract data type or linear data structure from which elements can be inserted at the rear(back) of the queue and elements can be deleted from the front(head) of the queue. The operations allowed in the queue are:insert an element at the reardelete element from the frontget the last elementget the first elementcheck the size
3 min read
Why can't a Priority Queue wrap around like an ordinary Queue?
Priority Queue: A priority queue is a special type of queue in which each element is assigned a priority value. And elements are served based on their priority. This means that elements with higher priority are served first. However, if elements with the same priority occur, they will be served in the order in which they were queued. A priority que
3 min read
Can we use Simple Queue instead of Priority queue to implement Dijkstra's Algorithm?
What is Dijkstra's Algorithm? Dijkstra's Algorithm is used for finding the shortest path between any two vertices of a graph. It uses a priority queue for finding the shortest path. For more detail, about Dijkstra's Algorithm, you can refer to this article. Why Dijkstra's Algorithm uses a Priority Queue? We use min heap in Dijkstra's Algorithm beca
2 min read
Turn a Queue into a Priority Queue
What is Queue?Queue is an abstract data type that is open at both ends. One end is always used to insert data (enqueue) which is basically the rear/back/tail end and the other which is the front end is used to remove data (dequeue). Queue follows First-In-First-Out (FIFO) methodology, i.e., "the data item stored first will be accessed first". Decla
9 min read
Why does Queue have front but Priority-queue has top in stl?
Why does the queue have front but the priority queue has top in stl? The main difference between a queue and a priority queue is that a queue follows the FIFO (First-In-First-Out) principle, while a priority queue follows a specific priority order. In other words, the elements in a queue are processed in the order they were added, whereas the eleme
8 min read
What is Priority Queue | Introduction to Priority Queue
A priority queue is a type of queue that arranges elements based on their priority values. Elements with higher priority values are typically retrieved or removed before elements with lower priority values. Each element has a priority value associated with it. When we add an item, it is inserted in a position based on its priority value. There are
15+ min read
Implementation of Non-Preemptive Shortest Job First using Priority Queue
Read here for Shortest Job First Scheduling algorithm for same arrival times.Shortest job first (SJF) or shortest job next, is a scheduling policy that selects the waiting process with the smallest execution time to execute next.In this article, we will implement the Shortest Job First Scheduling algorithm (SJF) using a priority queue, so that we c
12 min read
Indexed Priority Queue with Implementation
Priority queue is a data structure in which data is stored on basis of its priority. In an Indexed Priority Queue, data is stored just like standard priority queue and along with this, the value of a data can be updated using its key. It is called "indexed" because a hash map can be used to store the index in container using the key of key-value pa
8 min read
Introduction and Array Implementation of Queue
Similar to Stack, Queue is a linear data structure that follows a particular order in which the operations are performed for storing data. The order is First In First Out (FIFO). One can imagine a queue as a line of people waiting to receive something in sequential order which starts from the beginning of the line. It is an ordered list in which in
13 min read
Implementation of Queue in Javascript
In This article, we will be implementing Queue data structure in JavaScript. A Queue works on the FIFO(First in First Out) principle. Hence, it performs two basic operations which are the addition of elements at the end of the queue and the removal of elements from the front of the queue. Like Stack, Queue is also a linear data structure.  Note: As
6 min read
Difference between PriorityQueue and Queue Implementation in Java
Java Queue InterfaceThe Java.util package has the interface Queue, which extends the Collection interface. It is employed to preserve the components that are handled according to the FIFO principle. It is an ordered list of items where new elements are added at the end and old elements are removed from the beginning. Being an interface, the queue n
5 min read
Array implementation of queue (Simple)
Please note that a simple array implementation discussed here is not used in practice as it is not efficient. In practice, we either use Linked List Implementation of Queue or circular array implementation of queue. The idea of this post is to give you a background as to why we need a circular array implementation. To implement a queue using a simp
12 min read
Implementation of Chinese Remainder theorem (Inverse Modulo based implementation)
We are given two arrays num[0..k-1] and rem[0..k-1]. In num[0..k-1], every pair is coprime (gcd for every pair is 1). We need to find minimum positive number x such that: x % num[0] = rem[0], x % num[1] = rem[1], ....................... x % num[k-1] = rem[k-1] Example: Input: num[] = {3, 4, 5}, rem[] = {2, 3, 1} Output: 11 Explanation: 11 is the sm
11 min read
Insertion in an empty List in the circular linked list
A circular linked list is a type of data structure where each node points to the next one, and the last node connects back to the first, forming a circle. This setup allows you to loop through the list without stopping. Knowing how to insert a node into an empty circular linked list is important in creating circular linked list. Insertion in an emp
5 min read
Priority Queue using Doubly Linked List
Given Nodes with their priority, implement a priority queue using doubly linked list. Prerequisite : Priority Queue push(): This function is used to insert a new data into the queue.pop(): This function removes the element with the lowest priority value from the queue.peek() / top(): This function is used to get the lowest priority element in the q
11 min read
Python | Queue using Doubly Linked List
A Queue is a collection of objects that are inserted and removed using First in First out Principle(FIFO). Insertion is done at the back(Rear) of the Queue and elements are accessed and deleted from first(Front) location in the queue. Queue Operations:1. enqueue() : Adds element to the back of Queue. 2. dequeue() : Removes and returns the first ele
3 min read
Difference between a Static Queue and a Singly Linked List
Static Queue: A queue is an ordered list of elements. It always works in first in first out(FIFO) fashion. All the elements get inserted at the REAR and removed from the FRONT of the queue. In implementation of the static Queue, an array will be used so all operation of queue are index based which makes it faster for all operations except deletion
15+ min read
Priority Queue using Linked List
Implement Priority Queue using Linked Lists. push(): This function is used to insert a new data into the queue.pop(): This function removes the element with the highest priority from the queue.peek() / top(): This function is used to get the highest priority element in the queue without removing it from the queue.Priority Queues can be implemented
12 min read
Linked List Implementation in C#
A LinkedList is a linear data structure which stores element in the non-contiguous location. The elements in a linked list are linked with each other using pointers. Or in other words, LinkedList consists of nodes where each node contains a data field and a reference(link) to the next node in the list. In C#, LinkedList is the generic type of colle
6 min read