0% found this document useful (0 votes)
3 views19 pages

Queues

A queue is a data structure that follows the First In, First Out (FIFO) principle, allowing elements to be added at one end and removed from the other. Various implementations in Python include using lists, collections.deque, and the queue.Queue module, each with different performance characteristics. Additionally, queues can be implemented using linked lists, which offer dynamic sizing but require more memory due to node pointers.

Uploaded by

nomiiking552527
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views19 pages

Queues

A queue is a data structure that follows the First In, First Out (FIFO) principle, allowing elements to be added at one end and removed from the other. Various implementations in Python include using lists, collections.deque, and the queue.Queue module, each with different performance characteristics. Additionally, queues can be implemented using linked lists, which offer dynamic sizing but require more memory due to node pointers.

Uploaded by

nomiiking552527
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 19

Queues

What is a queue?
• It is an ordered group of homogeneous items of
elements.
• Queues have two ends:
• Elements are added at one end.
• Elements are removed from the other end.
• The element added first is also removed first (FIFO:
First In, First Out).
Queue Specification
• Definitions: (provided by the user)
• MAX_ITEMS: Max number of items that might be on the
queue
• ItemType: Data type of the items on the queue

• Operations
– MakeEmpty
– Boolean IsEmpty
– Boolean IsFull
– Enqueue (ItemType newItem)
– Dequeue (ItemType& item)
Enqueue (ItemType newItem)

• Function: Adds newItem to the rear of the queue.


• Preconditions: Queue has been initialized and is not full.
• Postconditions: newItem is at rear of queue.
Dequeue (ItemType& item)

• Function: Removes front item from queue and returns it in item.


• Preconditions: Queue has been initialized and is not empty.
• Postconditions: Front element has been removed from queue and
item is a copy of removed element.
Implementation issues

• Implement the queue as a circular structure.


• How do we know if a queue is full or empty?
• Initialization of front and rear.
• Testing for a full or empty queue.
Operations associated with queue are:

Enqueue: Adds an item to the queue. If the queue is full, then


it is said to be an Overflow condition – Time Complexity : O(1)
Dequeue: Removes an item from the queue. The items are
popped in the same order in which they are pushed. If the
queue is empty, then it is said to be an Underflow condition –
Time Complexity : O(1)
Front: Get the front item from queue – Time Complexity : O(1)
Rear: Get the last item from queue – Time Complexity : O(1)
Implement a Queue in Python

There are various ways to implement a queue in Python. This


article covers the implementation of queue using data
structures and modules from Python library. Python Queue can
be implemented by the following ways:

list
collections.deque
queue.Queue
Implementation using
Make front point listelement preceding the front
to the
List element
is a Python’s
in the built-in
queue (onedatamemory
structure that can
location be used
will be
as wasted).
a queue. Instead of enqueue() and dequeue(),
append() and pop() function is used.

However, lists are quite slow for this purpose because


inserting or deleting an element at the beginning
requires shifting all of the other elements by one,
requiring O(n) time.

The code simulates a queue using a Python list. It adds


elements ‘a’, ‘b’, and ‘c’ to the queue and then dequeues
them, resulting in an empty queue at the end. The
output shows the initial queue, elements dequeued (‘a’,
‘b’, ‘c’), and the queue’s empty state.
queue = []
Initialize front and rear
queue.append('a')
queue.append('b')
queue.append('c')
print("Initial queue")
print(queue)
print("\nElements dequeued from
queue")
print(queue.pop(0))
print(queue.pop(0))
print(queue.pop(0))
print("\nQueue after removing
elements")
print(queue)
Implementation using
collections.deque
Queue in Python can be implemented using deque class from the collections
module.

Deque is preferred over list in the cases where we need quicker append and
pop operations from both the ends of container, as deque provides an O(1)
time complexity for append and pop operations as compared to list which
provides O(n) time complexity.

Instead of enqueue and deque, append() and popleft() functions are used.
The code uses a deque from the collections module to represent a queue.

It appends ‘a’, ‘b’, and ‘c’ to the queue and dequeues them with q.popleft(),
Queue
resulting is empty
in an empty queue.
now!!
Uncommenting q.popleft() after the queue is empty would raise an IndexError.

The coderear == front


demonstrates queue operations and handles an empty queue
scenario.
from collections import deque
q = deque()
q.append('a')
q.append('b')
q.append('c')
print("Initial queue")
print(q)
print("\nElements dequeued from the queue")
print(q.popleft())
print(q.popleft())
print(q.popleft())

print("\nQueue after removing elements")


print(q)
Implementation using
queue.Queue
Queue is built-in module of Python which is used to implement a queue.
queue.Queue(maxsize) initializes a variable to a maximum size of maxsize.
A maxsize of zero ‘0’ means a infinite queue. This Queue follows FIFO rule.
private:
There are various functions available in this module:
int front;
•maxsize – Number of items allowed in the queue.
int rear;
•empty() – Return True if the queue is empty, FalseItemType*
otherwise.items;
int maxQue;
•full() – Return True if there are maxsize items}; in the queue. If the queue was
initialized with maxsize=0 (the default), then full() never returns True.

•get() – Remove and return an item from the queue. If queue is empty, wait until
an item is available.

•get_nowait() – Return an item if one is immediately available, else raise


QueueEmpty.

•put(item) – Put an item into the queue. If the queue is full, wait until a free slot is
available before adding the item.

•put_nowait(item) – Put an item into the queue without blocking. If no free slot is
immediately available, raise QueueFull.
Example: This code utilizes the Queue class from the queue
module.

It starts with an empty queue and fills it with ‘a’, ‘b’, and ‘c’.
After dequeuing, the queue becomes empty, and ‘1’ is
added.

Despite being empty earlier, it remains full, as the maximum


size is set to 3.

The code demonstrates queue operations, including


checking for fullness and emptiness.
0
from queue import Queue Full: True
Elements dequeued from the queue
q = Queue(maxsize = 3) a
print(q.qsize()) b
q.put('a') c
Empty: True
q.put('b') Empty: False
q.put('c') Full: False
print("\nFull: ", q.full())
print("\nElements dequeued from the queue")
print(q.get())
print(q.get())
print(q.get())
print("\nEmpty: ", q.empty())
q.put(1)
print("\nEmpty: ", q.empty())
print("Full: ", q.full())
Queue Implementation Using
Linked Lists
Reasons for using linked lists to implement queues:
•Dynamic size: The queue can grow and shrink
dynamically, unlike with arrays.

•No shifting: The front element of the queue can be


removed (enqueue) without having to shift other
elements in the memory.

Reasons for not using linked lists to implement queues:


•Extra memory: Each queue element must contain the
address to the next element (the next linked list node).

•Readability: The code might be harder to read and


write for some because it is longer and more complex.
This is how a queue can be implemented using a linked
list.
class Node: def dequeue(self):
def __init__(self, data): if self.isEmpty():
self.data = data return "Queue is empty"
self.next = None temp = self.front
self.front = temp.next
class Queue: self.length -= 1
def __init__(self): if self.front is None:
self.front = None self.rear = None
self.rear = None return temp.data
self.length = 0
def peek(self):
def enqueue(self, element): if self.isEmpty():
new_node = Node(element) return "Queue is empty"
if self.rear is None: return self.front.data
self.front = self.rear = new_node
self.length += 1 def isEmpty(self):
return return self.length == 0
self.rear.next = new_node
self.rear = new_node def size(self):
self.length += 1 return self.length
def printQueue(self):
temp = self.front
while temp:
print(temp.data, end=" ")
temp = temp.next
print()

# Create a queue
myQueue = Queue()
myQueue.enqueue('A')
myQueue.enqueue('B')
myQueue.enqueue('C')
print("Queue: ", end="")
myQueue.printQueue()

print("Dequeue: ",
myQueue.dequeue())

print("Peek: ", myQueue.peek())

print("isEmpty: ",
myQueue.isEmpty())

print("Size: ", myQueue.size())

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy