0% found this document useful (0 votes)
3 views

Queue(1)

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Queue(1)

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Queue: Constructor

Create a Queue class that represents a first-in, first-out (FIFO) data


structure using a linked list implementation.

The Queue class should contain the following components:

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.

Algorithm for Queue Initialization (__init__ Method)

The __init__ method initializes the queue with a single element,


following these steps:

1. Create a New Node:


○ Use the Node class to create a new node containing the initial
value.
○ The node’s next attribute is automatically set to None during
its initialization in the Node class, so it has no link to any other
node.
2. Assign the Node to first and last Pointers:
○ Set self.first to new_node. This makes the new node the
first element in the queue.
○ Set self.last to new_node. Since there’s only one node at
this point, it is both the first and the last node.
3. Initialize Length:
○ Set self.length to 1, indicating that there is one element in
the queue.

Step-by-Step Code

Here’s the code as it follows the algorithm above:


python

Copy code

class Queue:

def __init__(self, value):

new_node = Node(value) # Step 1: Create a


new node with the given value

self.first = new_node # Step 2: Set the new


node as the first element

self.last = new_node # Step 2: Also set


the new node as the last element

self.length = 1 # Step 3: Set the


length of the queue to 1
Example Usage

python

Copy code

my_queue = Queue(5) # Initialize the queue with a


single element, 5

print("First:", my_queue.first.value) # Output: 5

print("Last:", my_queue.last.value) # Output: 5

print("Length:", my_queue.length) # Output: 1

After this initialization:

● my_queue.first.value will be 5, as it's the only element and thus


the first.
● my_queue.last.value will also be 5, since it’s both the first and
last node.
● my_queue.length will be 1, indicating that there is one node in the
queue.
Queue:Enqueue

Implement the enqueue method for the Queue class that adds a
new node with a given value to the end of the queue.

The method should perform the following tasks:

1. Create a new instance of the Node class using the provided


value.
2. If the queue is empty (i.e., self.first is None), set the
first and last attributes of the Queue class to point to the
new node.
3. If the queue is not empty, perform the following steps:
● Set the next attribute of the current last node to point
to the new node.
● Update the last attribute of the Queue class to point to
the new node.
4. Increment the length attribute of the Queue class by 1.
Algorithm for the enqueue Method

The enqueue method performs the following steps:

1. Create a New Node:


○ A new node (new_node) is created with the given
value.
○ This new node will be added to the end of the queue.
2. Check if the Queue is Empty:
○ If self.first is None, it means the queue is empty
(no elements in the queue).
○ In this case, set both self.first and self.last to
point to the new_node. This makes the new node both
the first and the last element of the queue.
3. Add to the End of the Queue (If Queue is Not Empty):
○ If the queue is not empty:
■ Set self.last.next to point to the new_node.
This links the current last node to the new node.
■ Update self.last to point to new_node, making
it the new last element in the queue.
4. Update the Length:
○ Increment self.length by 1 to reflect the addition of
the new element to the queue.
def enqueue(self,value):
new_node=Node(value)
if self.first==None:
self.first=new_node
self.last=new_node
else:
self.last.next=new_node
self.last=new_node
self.length+=1
Queue: Dequeue
Implement the dequeue method for the Queue class that removes the
first node from the queue and returns it.

The method should perform the following tasks:

1. If the queue is empty (i.e., the length is 0), return None.


2. Store a reference to the current first node in a temporary variable,
temp.
3. If the queue has only one node (i.e., the length is 1), set both the
first and last attributes of the Queue class to None.
4. If the queue has more than one node, perform the following
steps:
● Update the first attribute of the Queue class to point to
the next node in the queue.
● Set the next attribute of the removed node (stored in the
temporary variable) to None.
5. Decrement the length attribute of the Queue class by 1.
6. Return the removed node (stored in the temporary variable).
Algorithm for the dequeue Method

The dequeue method performs the following steps:

1. Check if the Queue is Empty:


○ If self.length == 0, it means the queue is empty, and there
are no elements to remove.
○ In this case, return None to indicate that no element was
dequeued.
2. Remove the Front Node:
○ If the queue is not empty:
■ Store the current front node (self.first) in a
temporary variable temp so that it can be returned later.
3. Handle Special Case (Queue has Only One Element):
○ If self.length == 1, it means there is only one element in
the queue (i.e., both first and last point to the same node).
■ In this case, set both self.first and self.last to
None because the queue will be empty after this
operation.
4. Update the Front of the Queue:
○ If there are more than one element in the queue:
■ Set self.first to the next node (self.first.next)
to remove the front element and shift the front pointer to
the next node.
5. Decrement the Queue Length:
○ Decrease self.length by 1 to reflect the removal of one
element.
6. Return the Removed Node:
○ Return the temp variable, which contains the removed node.
def dequeue(self):
if self.length==0:
return None

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.

The method should perform the following tasks:

● 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.

Algorithm for print_queue()

The print_queue method performs the following steps:

1. Check if the Queue is Empty:


○ If self.length == 0, print "Queue is empty" and exit the
method.
2. Iterate through the Queue:
○ Start from the first node (self.first).
○ Traverse the queue by following each node's next pointer and
print the value of each node.
○ Continue this until the last node is reached (when node.next
== None).
3. End the Method:
○ If there are elements in the queue, the values of all nodes are
printed in order.
○ If the queue is empty, a message is displayed indicating the
queue is empty.
Check if the Queue is Empty:

● The first step checks if self.length == 0. If this is


true, the method prints "Queue is empty" to notify the
user that no elements are available to print. After this, the
method exits.

Start from the First Node:

● If the queue is not empty, we begin from the


self.first node, which is the front of the queue.

Iterate through the Queue:

● A while loop is used to traverse the queue. The loop


continues as long as there is a node (current_node is
not None).
● For each node, we print the value of the node followed by
->, which indicates the link to the next node.
● We then update current_node to point to the next
node (current_node = current_node.next).

End of Queue:

● Once the loop completes, meaning we've reached the


last node (current_node == None), we print "None"
to indicate the end of the queue.
def print_queue(self):
if self.length == 0:
print("Queue is empty")
return

current_node = self.first

while current_node:
print(current_node.value, end=" -> ")
current_node = current_node.next

print("None")
Queue Operations Using List

1. enqueue(value): Add an element to the back of the queue.

● Operation: In Python, this can be done using the append() method.


● Time Complexity: The append() method on a list runs in O(1) time, meaning
it's an efficient operation.

2. dequeue(): Remove an element from the front of the queue.

● 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.

3. peek(): View the element at the front without removing it.

● Operation: Simply access the first element using queue[0].


● Time Complexity: This operation is O(1) since accessing an element by index in
a list is a constant-time operation.

4. is_empty(): Check whether the queue is empty.

● 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.

5. size(): Get the number of elements in the queue.

● Operation: Use len(queue) to get the number of elements.


● Time Complexity: O(1), since len() provides the size of the list in constant
time.
class Queue:

def __init__(self):

self.queue = []

def enqueue(self, value):

self.queue.append(value)

def dequeue(self):

if not self.is_empty():

return self.queue.pop(0)

else:

return "Queue is empty"

def peek(self):

if not self.is_empty():

return self.queue[0]

else:

return "Queue is empty"

def is_empty(self):

return len(self.queue) == 0

def size(self):

return len(self.queue)

You might also like