Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Program to Implement Queue Data Structure using Linked List
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
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Queue_structure:
def __init__(self):
self.head = None
self.last = None
def enqueue_operation(self, data):
if self.last is None:
self.head = Node(data)
self.last = self.head
else:
self.last.next = Node(data)
self.last = self.last.next
def dequeue_operation(self):
if self.head is None:
return None
else:
val_returned = self.head.data
self.head = self.head.next
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.