Open In App

Name some Queue implementations and compare them by efficiency of operations

Last Updated : 30 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

A queue is a linear data structure in which insertion is done from one end called the rear end and deletion is done from another end called the front end. It follows FIFO (First In First Out) approach. The insertion in the queue is called enqueue operation and deletion in the queue is called dequeue operation. 

A queue can be implemented in two ways:

  • Array implementation of queue
  • Linked List implementation of queue

Array implementation of the queue:

For the array implementation of the queue, we have to take an array of size n. We also use two pointers front and rear to keep track of the front element and the last position where a new element can be inserted respectively. All the functionalities are satisfied by using these two pointers. For more details about array implementation of a queue refer to this link.

Below is the code for array implementation of a queue.

C++




// C++ program to implement queue using array
 
#include <bits/stdc++.h>
using namespace std;
 
// Structure of a queue
struct Queue {
    int rear, front, s;
    int* q;
 
     
    Queue(int c)
    {
        front = rear = 0;
        s = c;
        q = new int;
    }
    ~Queue() { delete[] q; }
 
    // Function to insert element at
    // the rear end of the queue
    void enqueue(int data)
    {
        if (rear == s)
            cout << "Queue is full\n";
        else {
            q[rear] = data;
            rear++;
        }
        return;
    }
 
    // Function to delete element at
    // the front end of the queue
    void dequeue()
    {
        if (rear == front)
            cout << "Queue is empty\n";
        else
            front++;
    }
 
    // Function to display the queue
    void display()
    {
        if (rear == front)
            cout << "Queue is empty\n";
        else
            for (int i = front; i < rear; i++) {
                cout << q[i] << " ";
            }
    }
};
 
// Driver code
int main()
{
    Queue p(3);
    p.enqueue(10);
    p.enqueue(20);
    p.enqueue(30);
    p.display();
    cout << "\nAfter two deletion\n";
    p.dequeue();
    p.dequeue();
    p.display();
    return 0;
}


Java




/*package whatever //do not write package name here */
import java.io.*;
 
class GFG {
 
  // Class of a queue
  static class Queue {
    int rear, front, s;
    int q[];
 
    // Constructor of a queue
    Queue(int c)
    {
      front = 0;
      rear = 0;
      s = c;
      q = new int[s];
    }
 
    // Function to insert element at
    // the rear end of the queue
    void enqueue(int data)
    {
      if (rear == s)
        System.out.println("Queue is full");
      else {
        q[rear] = data;
        rear++;
      }
      return;
    }
 
    // Function to delete element at
    // the front end of the queue
    void dequeue()
    {
      if (rear == front)
        System.out.println("Queue is empty");
      else
        front++;
    }
 
    // Function to display the queue
    void display()
    {
      if (rear == front)
        System.out.println("Queue is empty");
      else
        for (int i = front; i < rear; i++) {
          System.out.print(q[i]+" ");
        }
    }
 
  }
 
  public static void main (String[] args) {
    Queue p = new Queue(3);
    p.enqueue(10);
    p.enqueue(20);
    p.enqueue(30);
    p.display();
    System.out.println("\nAfter two deletion");
    p.dequeue();
    p.dequeue();
    p.display();
  }
}
 
// This code is contributed by aadityaburujwale.


Python3




# Structure of a queue
class Queue:
   
      # Constructor of a queue
    def __init__(self, c):
        self.rear = 0
        self.front = 0
        self.s = c
        self.q = [0] * c
         
    # Function to insert element at
    # the rear end of the queue
    def enqueue(self, data):
        if self.rear == self.s:
            print("Queue is full")
        else:
            self.q[self.rear] = data
            self.rear += 1
             
    # Function to delete element at
    # the front end of the queue
    def dequeue(self):
        if self.rear == self.front:
            print("Queue is empty")
        else:
            self.front += 1
             
    # Function to display the queue
    def display(self):
        if self.rear == self.front:
            print("Queue is empty")
        else:
            for i in range(self.front, self.rear):
                print(self.q[i], end=" ")
            print()
 
# Driver code
if __name__ == "__main__":
    p = Queue(3)
    p.enqueue(10)
    p.enqueue(20)
    p.enqueue(30)
    p.display()
    print("After two deletion")
    p.dequeue()
    p.dequeue()
    p.display()
     
# This code is contributed by akashish__


C#




// C# program to implement queue using array
 
using System;
 
public class GFG {
 
  // Class of a queue
  class Queue {
    public int rear, front, s;
    public int[] q;
 
    // Constructor of a queue
    public Queue(int c)
    {
      front = 0;
      rear = 0;
      s = c;
      q = new int[s];
    }
 
    // Function to insert element at
    // the rear end of the queue
    public void enqueue(int data)
    {
      if (rear == s)
        Console.WriteLine("Queue is full");
      else {
        q[rear] = data;
        rear++;
      }
      return;
    }
 
    // Function to delete element at
    // the front end of the queue
    public void dequeue()
    {
      if (rear == front)
        Console.WriteLine("Queue is empty");
      else
        front++;
    }
 
    // Function to display the queue
    public void display()
    {
      if (rear == front)
        Console.WriteLine("Queue is empty");
      else
        for (int i = front; i < rear; i++) {
          Console.Write(q[i] + " ");
        }
    }
  }
 
  static public void Main()
  {
 
    Queue p = new Queue(3);
    p.enqueue(10);
    p.enqueue(20);
    p.enqueue(30);
    p.display();
    Console.WriteLine("\nAfter two deletion");
    p.dequeue();
    p.dequeue();
    p.display();
  }
}
 
// This code is contributed by lokesh.


Javascript




// JS program to implement queue using array
 
// Structure of a queue
class Queue {
    constructor() {
        this.rear = 0;
        this.front = 0;
        this.q = new Array;
    }
 
    // Function to insert element at
    // the rear end of the queue
    enqueue(data) {
        if (this.rear == 3)
            console.log("Queue is full");
        else {
            this.q[this.rear] = data;
            this.rear++;
        }
        return;
    }
 
    // Function to delete element at
    // the front end of the queue
    dequeue() {
        if (this.rear == this.front)
            console.log("Queue is empty");
        else
            this.front++;
    }
 
    // Function to display the queue
    display() {
        if (this.rear == this.front)
            console.log("Queue is empty");
        else
            for (let i = this.front; i < this.rear; i++) {
                console.log(this.q[i], " ");
            }
    }
};
 
 
// Driver code
let p = new Queue;
p.enqueue(10);
p.enqueue(20);
p.enqueue(30);
p.display();
console.log("After two deletion");
p.dequeue();
p.dequeue();
p.display();
 
// This code is contributed by adityamaharshi21


Output

10 20 30 
After two deletion
30 

Time Complexity:

Insertion: O(1)
Deletion: O(1)
Searching: O(n)

Space Complexity: O(n)

Linked List Implementation of the queue:

For implementing a queue using linked list we don’t need to know the size beforehand like array. The dynamic property of linked list allows queue to grow to any size. In case of a linked list also we use two pointers front and rear that perform the same task as in array. For more details about linked list implementation refer to this link.

Below is the code for linked list implementation of queue.

C++




// Program to implement queue using linked list
 
#include <bits/stdc++.h>
using namespace std;
 
// Structure of a queue node
struct Qnode {
    int d;
    struct Qnode* next;
};
 
// Structure of a queue
struct Q {
    struct Qnode *front, *rear;
};
 
// Function to create a new node
struct Qnode* newNode(int k)
{
    struct Qnode* t
        = (struct Qnode*)malloc(sizeof(struct Qnode));
    t->d = k;
    t->next = NULL;
    return t;
}
 
// Function to create a queue
struct Q* createQ()
{
    struct Q* q = (struct Q*)malloc(sizeof(struct Q));
    q->front = q->rear = NULL;
    return q;
}
 
// Function to enqueue a new value
void enqueue(struct Q* q, int data)
{
    struct Qnode* t = newNode(data);
    if (q->rear == NULL) {
        q->front = q->rear = t;
        return;
    }
    q->rear->next = t;
    q->rear = t;
}
 
// Function for implementing deque
void dequeue(struct Q* q)
{
    if (q->front == NULL)
        return;
    struct Qnode* t = q->front;
    q->front = q->front->next;
    if (q->front == NULL)
        q->rear = NULL;
    free(t);
}
 
// Driver code
int main()
{
    struct Q* q = createQ();
    enqueue(q, 10);
    enqueue(q, 20);
    enqueue(q, 30);
    dequeue(q);
 
    cout << "Queue front  " << q->front->d;
    cout << "\nQueue rear  " << q->rear->d;
    return 0;
}


Java




class Qnode {
    int d;
    Qnode next;
}
 
class Q {
    Qnode front, rear;
    Q() {
        front = rear = null;
    }
}
 
class Main {
    static Qnode newNode(int k) {
        Qnode t = new Qnode();
        t.d = k;
        t.next = null;
        return t;
    }
 
    static Q createQ() {
        Q q = new Q();
        return q;
    }
 
    static void enqueue(Q q, int data) {
        Qnode t = newNode(data);
        if (q.rear == null) {
            q.front = q.rear = t;
            return;
        }
        q.rear.next = t;
        q.rear = t;
    }
 
    static void dequeue(Q q) {
        if (q.front == null) {
            return;
        }
        Qnode t = q.front;
        q.front = q.front.next;
        if (q.front == null) {
            q.rear = null;
        }
        t = null;
    }
 
    public static void main(String[] args) {
        Q q = createQ();
        enqueue(q, 10);
        enqueue(q, 20);
        enqueue(q, 30);
        dequeue(q);
 
        System.out.println("Queue front: " + q.front.d);
        System.out.println("Queue rear: " + q.rear.d);
    }
}


Python




class Qnode:
    def __init__(self, d):
        self.d = d
        self.next = None
 
class Q:
    def __init__(self):
        self.front = None
        self.rear = None
 
def newNode(k):
    t = Qnode(k)
    return t
 
def createQ():
    q = Q()
    return q
 
def enqueue(q, data):
    t = newNode(data)
    if q.rear is None:
        q.front = q.rear = t
        return
    q.rear.next = t
    q.rear = t
 
def dequeue(q):
    if q.front is None:
        return
    t = q.front
    q.front = q.front.next
    if q.front is None:
        q.rear = None
    t = None
 
q = createQ()
enqueue(q, 10)
enqueue(q, 20)
enqueue(q, 30)
dequeue(q)
 
print("Queue front: ", q.front.d)
print("Queue rear: ", q.rear.d)


C#




public class Qnode
{
    public int d;
    public Qnode next;
 
    public Qnode(int val)
    {
        d = val;
        next = null;
    }
}
 
public class Q
{
    public Qnode front, rear;
 
    public Q()
    {
        front = rear = null;
    }
}
 
public class MainClass
{
    public static Qnode newNode(int k)
    {
        Qnode t = new Qnode(k);
        return t;
    }
 
    public static Q createQ()
    {
        Q q = new Q();
        return q;
    }
 
    public static void enqueue(Q q, int data)
    {
        Qnode t = newNode(data);
        if (q.rear == null)
        {
            q.front = q.rear = t;
            return;
        }
        q.rear.next = t;
        q.rear = t;
    }
 
    public static void dequeue(Q q)
    {
        if (q.front == null)
        {
            return;
        }
        Qnode t = q.front;
        q.front = q.front.next;
        if (q.front == null)
        {
            q.rear = null;
        }
        t = null;
    }
 
    public static void Main(string[] args)
    {
        Q q = createQ();
        enqueue(q, 10);
        enqueue(q, 20);
        enqueue(q, 30);
        dequeue(q);
 
        System.Console.WriteLine("Queue front: " + q.front.d);
        System.Console.WriteLine("Queue rear: " + q.rear.d);
    }
}
 
// This code is contributed by factworx412.


Javascript




// Program to implement queue using linked list
 
class QNode {
    constructor(data) {
    this.d = data;
    this.next = null;
    }
    }
     
    class Q {
    constructor() {
    this.front = this.rear = null;
    }
    }
     
    const newNode = data => new QNode(data);
     
    const createQ = () => new Q();
     
    const enqueue = (q, data) => {
    const t = newNode(data);
    if (q.rear === null) {
    q.front = q.rear = t;
    return;
    }
    q.rear.next = t;
    q.rear = t;
    };
     
    const dequeue = q => {
    if (q.front === null) return;
    const t = q.front;
    q.front = q.front.next;
    if (q.front === null) q.rear = null;
    };
     
    // Driver code
    const q = createQ();
    enqueue(q, 10);
    enqueue(q, 20);
    enqueue(q, 30);
    dequeue(q);
     
    console.log("Queue front: ", q.front.d);
    console.log("Queue rear: ", q.rear.d);
     
    // This code is contributed by aadityamaharshi21.


Output

Queue front  20
Queue rear  30

Time complexity: The time complexity of enqueue and dequeue operations in a queue implemented using linked list is O(1). This is because, in a linked list, insertion and deletion operations are performed in constant time.

Space complexity: The space complexity of a queue implemented using linked list is O(n), where n is the number of elements in the queue. This is because we need to allocate memory for each element in the queue and the size of the queue increases or decreases as elements are added or removed.

Note: For easy understanding only the enqueue() and deque() functionalities are shown here. For detailed implementation you can check the links provided for implementation.

Comparison:

Queue Operations Array Implementation Linked-List Implementation
Time Complexity Space Complexity Time Complexity Space Complexity
Enqueue  O (1) O (1) O (1) O (1)
Dequeue  O (1) O (1) O (1) O (1)
IsFull O (1) O (1) O (N) O (1)
IsEmpty O (1) O (1) O (1) O (1)
Peek O (1) O (1) O (1) O (1)

Related articles:



Similar Reads

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
Basic Operations in Stack Data Structure with Implementations
In order to make manipulations in a stack, there are certain operations provided to us for Stack, which include: push() to insert an element into the stackpop() to remove an element from the stacktop() Returns the top element of the stack.isEmpty() returns true if the stack is empty else false.size() returns the size of the stack.In this post, we w
14 min read
Basic Operations on Binary Tree with Implementations
The tree is a hierarchical Data Structure. A binary tree is a tree that has at most two children. The node which is on the left of the Binary Tree is called “Left-Child” and the node which is the right is called “Right-Child”. Also, the smaller tree or the subtree in the left of the root node is called the “Left sub-tree” and that is on the right i
65 min read
What is the time efficiency of the push(), pop(), isEmpty() and peek() operations of Stacks?
Stack is a linear data structure that follows the LIFO (last in first out) order i.e., the data are entered from one end and while they are removed, they will be removed from the same end. The few most performed operations in a stack are: push()pop()isEmpty()peek()Now let us check the time efficiency of the operations: 1. push(): This function is c
2 min read
Minimize steps to make two integers equal by incrementing them or doing bitwise OR of them
Given two positive integers A and B. The task is to make them equal using minimum operations such that: A = A + 1 (increase a by 1).B = B + 1 (increase b by 1).A = A | B (replace A with the bitwise OR of A and B). Examples: Input: A = 5, B = 9Output: 4Explanation: It is better to use first operation i.e increase A by 1 four times, Input: A = 2, B =
8 min read
Maximize product of sum of speeds of K workers and their minimum efficiency
Given an integer N, representing the number of workers, an array speed[ ], where speed[i] represents the speed of the ith worker, and an array efficiency[ ], where efficiency[i] represents the efficiency of the ith worker, and an integer K, the task is to select K workers such that the ( Sum of speeds of all the workers ) * ( Minimum efficiency of
9 min read
Understanding "Efficiency" when working with Data Structures and Algorithms
What is Efficient Programming?Efficient programming is programming in a manner that, when the program is executed, uses a low amount of overall resources pertaining to computer hardware.  Practicing to create a small file size and low resource algorithm results in an efficient program. Below are some important concepts you should know to understand
8 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
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. [caption width="800"]Queue Data structure[/caption]The operations allowed in the queue are:insert an element at the reardelete element from the frontget
3 min read
Difference Between Linear Queue and Circular 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
4 min read
Practice Tags :