Related Topics

Data Structure
class Queue:
def __init__(self):
self.queue = []
def enqueue(self, item):
self.queue.append(item)
def dequeue(self):
if len(self.queue) < 1:
return None
return self.queue.pop(0)
def display(self):
print(self.queue)
Implementing a queue using a linked list:
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class Queue:
def __init__(self):
self.head = None
self.tail = None
def enqueue(self, item):
new_node = Node(item)
if self.tail is None:
self.head = new_node
self.tail = new_node
return
self.tail.next = new_node
self.tail = new_node
def dequeue(self):
if self.head is None:
return None
temp = self.head
self.head = self.head.next
if self.head is None:
self.tail = None
return temp.data
def display(self):
temp = self.head
while temp:
print(temp.data, end=" ")
temp = temp.next
In both cases, enqueue()
is used to add an element to the end of the queue, dequeue()
is used to remove an element from the front of the queue, and display()
is used to display the contents of the queue. The main difference between the two implementations is that the array implementation uses append()
and pop(0)
to add and remove elements from the queue, while the linked list implementation uses a Node
class to store the data and the next
pointer to maintain the queue order.




Popular Category
Topics for You
Go through our study material. Your Job is awaiting.