Python Program to Implement Queue Data Structure using Linked List

PythonServer Side ProgrammingProgramming

Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

Practical Data Science using Python

22 Lectures 6 hours

When it is required to implement a queue data structure using a linked list, a method to add (enqueue operation) elements to the linked list, and a method to delete (dequeue operation) the elements of the linked list are defined.

Below is a demonstration for the same −

Example

Live Demo

class Node:
def __init__(self, data):
self.data = data
self.next = None

class Queue_structure:
def __init__(self):
self.last = None

def enqueue_operation(self, data):
if self.last is None:
else:
self.last.next = Node(data)
self.last = self.last.next

def dequeue_operation(self):
return None
else:
return val_returned

my_instance = Queue_structure()
while True:
print('enqueue <value>')
print('dequeue')
print('quit')
my_input = input('What operation would you like to perform ? ').split()

operation = my_input[0].strip().lower()
if operation == 'enqueue':
my_instance.enqueue_operation(int(my_input[1]))
elif operation == 'dequeue':
dequeued = my_instance.dequeue_operation()
if dequeued is None:
print('The queue is empty.')
else:
print('The deleted element is : ', int(dequeued))
elif operation == 'quit':
break

Output

enqueue <value>
dequeue
quit
What operation would you like to perform ? enqueue 45
enqueue <value>
dequeue
quit
What operation would you like to perform ? enqueue 12
enqueue <value>
dequeue
quit
What operation would you like to perform ? dequeue
The deleted element is : 45
enqueue <value>
dequeue
quit
What operation would you like to perform ? quit

Explanation

• The ‘Node’ class is created.

• Another ‘Queue_structure’ class with required attributes is created.

• It has an ‘init’ function that is used to initialize the first element, i.e the ‘head’ to ‘None’.

• A method named enqueue_operation’ is defined, that helps add a value to the queue.

• Another method named ‘dequeue_operation’ is defined, that helps delete a value from the queue, and returns the deleted value.

• An instance of the ‘Queue_structure’ is created.

• Three options are given, such as ‘enqueue’, ‘dequeue’, and ‘quit’.

• The ‘enqueue’ option adds a specific value to the stack.

• The ‘dequeue’ option deletes the element from the queue.

• The ‘quit’ option comes out of the loop.

• Based on the input/choice by user, the respective operations are performed.

• This output is displayed on the console.

Updated on 14-Apr-2021 13:26:46