Open In App

Python | Queue using Doubly Linked List

Last Updated : 05 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 element from the queue.
3. first()       : Returns the first element of the queue without removing it.
4. size()        : returns the number of elements in the Queue.
5. isEmpty()     : Return True if Queue is Empty else return False.
6. printqueue()  : Print all elements of the Queue.

Below is the implementation of the above-mentioned Queue operations using Doubly LinkedList in Python:

Python3




# A complete working Python program to demonstrate all
# Queue operations using doubly linked list
  
# Node class
class Node:
  
# Function to initialise the node object
    def __init__(self, data):
        self.data = data # Assign data
        self.next = None # Initialize next as null
        self.prev = None # Initialize prev as null
          
          
# Queue class contains a Node object
class Queue:
  
    # Function to initialize head
    def __init__(self):
        self.head = None
        self.last=None
          
  
# Function to add an element data in the Queue
    def enqueue(self, data):
        if self.last is None:
            self.head =Node(data)
            self.last =self.head
        else:
            self.last.next = Node(data)
            self.last.next.prev=self.last
            self.last = self.last.next
              
              
              
# Function to remove first element and return the element from the queue
    def dequeue(self):
  
        if self.head is None:
            return None
        else:
            temp= self.head.data
            self.head = self.head.next
            self.head.prev=None
            return temp
  
  
# Function to return top element in the queue
    def first(self):
  
        return self.head.data
  
  
# Function to return the size of the queue
    def size(self):
  
        temp=self.head
        count=0
        while temp is not None:
            count=count+1
            temp=temp.next
        return count
      
      
# Function to check if the queue is empty or not     
    def isEmpty(self):
  
        if self.head is None:
            return True
        else:
            return False
              
  
# Function to print the stack
    def printqueue(self):
          
        print("queue elements are:")
        temp=self.head
        while temp is not None:
            print(temp.data,end="->")
            temp=temp.next
      
          
# Code execution starts here         
if __name__=='__main__':
  
# Start with the empty queue
  queue = Queue()
  
  print("Queue operations using doubly linked list")
  
# Insert 4 at the end. So queue becomes 4->None 
  queue.enqueue(4)
  
# Insert 5 at the end. So queue becomes 4->5None 
  queue.enqueue(5)
  
# Insert 6 at the end. So queue becomes 4->5->6->None 
  queue.enqueue(6)
  
# Insert 7 at the end. So queue becomes 4->5->6->7->None 
  queue.enqueue(7)
  
# Print the queue
  queue.printqueue()
  
# Print the first element
  print("\nfirst element is ",queue.first())
  
# Print the queue size
  print("Size of the queue is ",queue.size())
  
# remove the first element
  queue.dequeue()
  
# remove the first element
  queue.dequeue()
  
# first two elements are removed
# Print the queue
  print("After applying dequeue() two times")
  queue.printqueue()
  
# Print True if queue is empty else False
  print("\nqueue is empty:",queue.isEmpty())


Output:

Queue operations using doubly linked list
queue elements are:
4->5->6->7->
first element is  4
Size of the queue is  4
After applying dequeue() two times
queue elements are:
6->7->
queue is empty: False

Time Complexity for operations:

  • enqueue(): O(1)
  • dequeue():O(1)
  • first(): O(1)
  • size(): O(N)
  • isEmpty():  O(1)
  • printStack():O(N)

Auxiliary Space required for operations:

  • enqueue(): O(1)
  • dequeue():O(1)
  • first(): O(1)
  • size(): O(1)
  • isEmpty():  O(1)
  • printStack():O(1)


Previous Article
Next Article

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
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
Difference between Singly linked list and Doubly linked list
Introduction to Singly linked list : A singly linked list is a set of nodes where each node has two fields 'data' and 'link'. The 'data' field stores actual piece of information and 'link' field is used to point to next node. Basically the 'link' field stores the address of the next node. Introduction to Doubly linked list : A Doubly Linked List (D
2 min read
When is Doubly Linked List more Efficient than Singly Linked List?
Did you know there are some cases where a Doubly Linked List is more efficient than a Singly Linked List, even though it takes more memory compared to a Singly Linked List? What are those Cases? Well, we will discuss that in the following article, But first, let's talk about Singly and linked lists: What is a Singly Linked List?A singly linked list
4 min read
Is two way linked list and doubly linked list same?
Yes, a two-way linked list and a doubly linked list are the same. Both terms refer to a type of linked list where each node contains a reference to the next node as well as the previous node in the sequence. The term “two-way” emphasizes the ability to move in both directions through the list, while “doubly” highlights that there are two links per
3 min read
XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
In the previous post, we discussed how a Doubly Linked can be created using only one space for the address field with every node. In this post, we will discuss the implementation of a memory-efficient doubly linked list. We will mainly discuss the following two simple functions. A function to insert a new node at the beginning.A function to travers
10 min read
XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
In this post, we're going to talk about how XOR linked lists are used to reduce the memory requirements of doubly-linked lists. We know that each node in a doubly-linked list has two pointer fields which contain the addresses of the previous and next node. On the other hand, each node of the XOR linked list requires only a single pointer field, whi
15+ min read
Construct a Doubly linked linked list from 2D Matrix
Given a 2D matrix, the task is to convert it into a doubly-linked list with four pointers that are next, previous, up, and down, each node of this list should be connected to its next, previous, up, and down nodes.Examples: Input: 2D matrix 1 2 3 4 5 6 7 8 9 Output: Approach: The main idea is to construct a new node for every element of the matrix
15+ 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
Priority Queue using Queue and Heapdict module in Python
Priority Queue is an extension of the queue with the following properties. An element with high priority is dequeued before an element with low priority. If two elements have the same priority, they are served according to their order in the queue. queue.PriorityQueue(maxsize) It is a constructor for a priority queue. maxsize is the number of eleme
3 min read
three90RightbarBannerImg