Queue(1)
Queue(1)
1. A Node class, which serves as the building block for the linked list.
The Node class should have an __init__ method that initializes the
following attributes:
● value: The value of the node.
● next: A reference to the next node in the list, initialized to None.
2. The Queue class should have an __init__ method that initializes the
queue with a single node, using the given value. The __init__
method should perform the following tasks:
● Create a new instance of the Node class using the provided
value.
● Set the first attribute of the Queue class to point to the new
node.
● Set the last attribute of the Queue class to point to the new
node.
● Initialize a length attribute for the Queue class, which
represents the current number of nodes in the queue, and set it
to 1.
Queue Class Structure
A queue is a linear data structure that follows the First In, First Out (FIFO)
principle, where elements are added to the back and removed from the
front.
● Attributes:
○ first: Points to the first node in the queue (front of the
queue).
○ last: Points to the last node in the queue (end of the queue).
○ length: Keeps track of the total number of nodes in the queue.
Step-by-Step Code
Copy code
class Queue:
python
Copy code
Implement the enqueue method for the Queue class that adds a
new node with a given value to the end of the queue.
temp=self.first
if self.length==1 :
self.first=None
self.last=None
else:
self.first=self.first.next
temp.next=None
self.length-=1
return temp
Problem Statement:
Implement a method print_queue() for the Queue class that prints the
elements of the queue from front to back (i.e., starting from the first node to
the last node). The method should traverse the entire queue and print each
element's value in order.
● If the queue is empty (i.e., the length is 0), print "Queue is empty".
● If the queue contains one or more elements, iterate through the
queue starting from the first node and print the value of each
node.
End of Queue:
current_node = self.first
while current_node:
print(current_node.value, end=" -> ")
current_node = current_node.next
print("None")
Queue Operations Using List
● Operation: In Python, you can use the pop(0) method to remove the element at
the front (index 0) of the list.
● Time Complexity: pop(0) takes O(n) time because, after removing the first
element, all other elements need to be shifted one position forward. This can
lead to inefficiency when performing a large number of dequeues.
● Operation: You can check if the list is empty by simply checking its length using
len(queue) == 0.
● Time Complexity: This is O(1) since len() in Python returns the size of the list
in constant time.
def __init__(self):
self.queue = []
self.queue.append(value)
def dequeue(self):
if not self.is_empty():
return self.queue.pop(0)
else:
def peek(self):
if not self.is_empty():
return self.queue[0]
else:
def is_empty(self):
return len(self.queue) == 0
def size(self):
return len(self.queue)