Open In App

Implementation of Queue using List in Python

Last Updated : 14 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A queue is a linear data structure that follows the FIFO (First In First Out) principle. The first element added is the first one to be removed. With a queue, the least recently added item is removed first. A good example of a queue is any queue of consumers for a resource where the consumer that came first is served first. In Python, we can implement a queue using both a regular list and a circular list.

Queue
Queue

1. Queue Implementation Using List

The simplest way to implement a queue is using Python's built-in list. In this implementation, we can perform the following operations:

  • Enqueue: Adds new elements to the end of the queue. Checks if the queue has space before insertion, then increments the size.
  • Dequeue: Removes the front element by shifting all remaining elements one position to the left. Decrements the queue size after removal.
  • getFront: Returns the first element of the queue if it’s not empty. Returns -1 if the queue is empty.
  • Display: Iterates through the queue from the front to the current size and prints each element.

Below is the illustration:


Here’s how we can implement the queue using a list:

Python
# Python program to implement 
# queue using array.

class Queue:
    def __init__(self, q_size):
        self.arr = [0] * q_size
        self.size = 0
        self.capacity = q_size
        self.front = 0
    
    # Function to add an element
    # to queue.
    def enqueue(self, x):
        
        # If queue is full
        if self.size == self.capacity:
            return
        
        self.arr[self.size] = x
        
        # Increment queue size.
        self.size += 1
    
    # Function to pop front 
    # element from queue.
    def dequeue(self):
        
        # If queue is empty 
        if self.size == 0:
            return
        
        # Shift all the elements 
        # to the left.
        for i in range(1, self.size):
            self.arr[i-1] = self.arr[i]
        
        # decrement queue size 
        self.size -= 1
    
    # Function which returns 
    # the front element.
    def getFront(self):
        
        # If queue is empty
        if self.size == 0:
            return -1
        
        return self.arr[self.front]
    
    # Function which prints
    # the elements of array.
    def display(self):
        
        for i in range(self.front, self.size):
            print(self.arr[i], end=" ")
        print()

if __name__ == "__main__":
    q = Queue(4)
    
    q.enqueue(1)
    q.enqueue(2)
    q.enqueue(3)
    print(q.getFront())
    q.dequeue()
    q.enqueue(4)
    q.display()

Output
1
2 3 4 

Time Complexity: O(1) for Enqueue (element insertion in the queue) as we simply increment pointer and put value in array, O(n) for Dequeue (element removing from the queue).
Auxiliary Space: O(n), as here we are using an n size array for implementing Queue

We can notice that the Dequeue operation is O(n) which is not acceptable. The enqueue and dequeue both operations should have O(1) time complexity. That is why if we wish to implement a queue using array (because of array advantages like cache friendliness and random access), we do circular list implementation of queue.

2. Queue Implementation Using Circular List

A circular queue is an optimized version of a queue that solves the problem of unused space in a list-based queue when elements are dequeued. In a circular queue, the last position is connected to the first, and both front and rear pointers wrap around when they reach the end of the list.

  1. Initialize an array of size n, where n is the maximum number of elements that the queue can hold.
  2. Initialize three variables (size, capacity, and front.)
  3. Enqueue: To enqueue an element x into the queue, do the following:
    1. Check if size == capacity (queue is full), display “Queue is full”.
    2. If not full: calculate rear = (front + size) % capacity and Insert value at the rear index. Increment size by 1.
  4. Dequeue: To dequeue an element from the queue, do the following:
    1. Check if size == 0 (queue is empty), display “Queue is empty”.
    2. If not empty: retrieve the element at the front index and move front = (front + 1) % capacity. Also, decrement size by 1 and return the removed element.

Illustration of Circular Queue:


Below is the implementation of above approach:

Python
# python3 program for insertion and
# deletion in Circular Queue
class MyQueue:
    def __init__(self, c):
        self.l = [None] * c
        self.cap = c  
        self.size = 0  
        self.front = 0  

    def getFront(self):
      
        # Check if queue is empty
        if self.size == 0:
            return None
        return self.l[self.front]  

    def getRear(self):
      
        # Check if queue is empty
        if self.size == 0:
            return None
          
        # Calculate rear index
        rear = (self.front + self.size - 1) % self.cap  
        return self.l[rear]  

    def enqueue(self, x):
      
        # Check if queue is full
        if self.size == self.cap:
            return
          
        # Calculate rear index
        rear = (self.front + self.size) % self.cap  
        self.l[rear] = x 
        self.size += 1 

    def dequeue(self):
      
        # Check if queue is empty
        if self.size == 0:
            return None
        res = self.l[self.front]  
        
        # Move front index circularly
        self.front = (self.front + 1) % self.cap 
        self.size -= 1  
        return res  

q = MyQueue(4)
q.enqueue(10)
print(q.getFront(), q.getRear())
q.enqueue(20)
print(q.getFront(), q.getRear())
q.enqueue(30)
print(q.getFront(), q.getRear())
q.enqueue(40)
print(q.getFront(), q.getRear())
q.dequeue()
print(q.getFront(), q.getRear())
q.dequeue()
print(q.getFront(), q.getRear())
q.enqueue(50)
print(q.getFront(), q.getRear())

Output
10 10
10 20
10 30
10 40
20 40
30 40
30 50

Complexity Analysis of Circular Queue Operations

Time Complexity:

Operation

Time Complexity

enqueue(x)

O(1)

dequeue()

O(1)

getFront()

O(1)

getRear()

O(1)

Auxiliary Space: O(size), where size is the number of elements in the circular queue.


Next Article
Article Tags :
Practice Tags :

Similar Reads