How would you implement a queue using linked list in Python?

Queue – Linked List Implementation

In the previous post, we introduced Queue and discussed array implementation. In this post, linked list implementation is discussed. The following two main operations must be implemented efficiently.
In a Queue data structure, we maintain two pointers, front and rear. The front points the first item of queue and rear points to last item.
enQueue[] This operation adds a new node after rear and moves rear to the next node.
deQueue[] This operation removes the front node and moves front to the next node.

C


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#include
#include
// A Linked List Node
struct Node
{
int data; // integer data
struct Node* next;// pointer to the next node
}*rear = NULL, *front = NULL;
// Utility function to allocate the new queue node
struct Node* newNode[int item]
{
// allocate a new node in a heap
struct Node* node = [struct Node*]malloc[sizeof[struct Node]];
// check if the queue [heap] is full. Then inserting an element would
// lead to heap overflow
if [node != NULL]
{
// set data in the allocated node and return it
node->data = item;
node->next = NULL;
return node;
}
else {
printf["\nHeap Overflow"];
exit[EXIT_FAILURE];
}
}
// Utility function to dequeue the front element
int dequeue[]// delete at the beginning
{
if [front == NULL]
{
printf["\nQueue Underflow"];
exit[EXIT_FAILURE];
}
struct Node* temp = front;
printf["Removing %d\n", temp->data];
// advance front to the next node
front = front->next;
// if the list becomes empty
if [front == NULL] {
rear = NULL;
}
// deallocate the memory of the removed node and optionally return the removed item
int item = temp->data;
free[temp];
return item;
}
// Utility function to add an item to the queue
void enqueue[int item]// insertion at the end
{
// allocate a new node in a heap
struct Node* node = newNode[item];
printf["Inserting %d\n", item];
// special case: queue was empty
if [front == NULL]
{
// initialize both front and rear
front = node;
rear = node;
}
else {
// update rear
rear->next = node;
rear = node;
}
}
// Utility function to return the top element in a queue
int peek[]
{
// check for an empty queue
if [front != NULL] {
return front->data;
}
else {
exit[EXIT_FAILURE];
}
}
// Utility function to check if the queue is empty or not
int isEmpty[] {
return rear == NULL && front == NULL;
}
int main[]
{
enqueue[1];
enqueue[2];
enqueue[3];
enqueue[4];
printf["The front element is %d\n", peek[]];
dequeue[];
dequeue[];
dequeue[];
dequeue[];
if [isEmpty[]] {
printf["The queue is empty"];
}
else {
printf["The queue is not empty"];
}
return 0;
}

DownloadRun Code

Python Program to Implement Queue Data Structure using Linked List

PythonServer Side ProgrammingProgramming

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 −

Node Class for Linked List

The Node Class used in the previous linked list tutorials is the same. Each Node holds an integer value and a pointer to the next Node in the linked list.

class Node[object]: def __init__[self, value: int, next_node: "Node" = None]: self.value = value self.next = next_node def __repr__[self]: return "Node ".format[self.value]

Queue Class

A queue is a First-In, First-Out [FIFO] abstract data type. The first value added to the queue will be the first value removed from the queue. My queue is implemented by a Queue Class and offers three common operations.

  • enqueue - Adds new value to the Queue.
  • dequeue - Retrieves and removes value from Queue.
  • is_empty - Returns True if the Queue is empty, othewise False.

All these operations are performed in constant time, O[1].

Here is one solution to implementing a Queue abstract data type using Python.

class Queue[object]: def __init__[self]: self.head = None self.tail = None def enqueue[self, value: int] -> None: new_node = Node[value] if self.head is None: self.head = new_node self.tail = self.head return self.tail.next = new_node self.tail = new_node def dequeue[self] -> int: if self.head is None: raise EmptyQueueException["Dequeue from empty queue."] value = self.head.value self.head = self.head.next if self.head is None: self.tail = None return value def is_empty[self]: return self.head is None

Unlike the Stack Abstract Data Type implmentation in Python which only uses a head pointer to the linked list, the Queue implementation contains both a head and tail pointer of the linked list. By maintaining a head and tail pointer in the linked list, we are able to guarantee that enqueue and dequeue are constant time O[1] operations. The head pointer is used during the dequeue operation, and the tail pointer is used during the enqueue operation.

How to implement a queue using a linked list

A queue is a first-in-first-out [FIFO] data structure. It can be implemented using a linked list.

The following are the three main operations that can be performed on a queue:

  • enqueue: adding an element to the end of the list.

  • dequeue: popping an item from the head of the list.

  • peeking: displaying the element at the tail of the list.

A queue implemented using a linked list.

Implement queue in Python using linked list

A linked list is a linear data structure in which each data object points to one another. To implement a queue with linked list, we will have to perform insertion and deletion of elements from a linked list such that the element which was added first can only be accessed. This is only possible when we will insert elements at the end of the linked list and access or delete elements from the start of the linked list. In this way the oldest element will be at the start of the linked list and can be accessed or deleted.

To implement a queue with linked list in python, we will first define a node object which will have the current element and will point to the node which will be inserted just after it. The Node can be implemented as follows in python.

class Node: def __init__[self,data]: self.data=data self.next=None

When we implement a queue with a linked list, it will have an element named front which will refer to the oldest element inserted in the linked list i.e the first element. All other elements can be accessed with the help of that.It will also contain a variable named queueSize which will contain the length of the queue. We can implement an empty queue in python as follows.

class Queue: def __init__[self]: self.front=None self.queueSize=0

Video liên quan

Bài mới nhất

Chủ Đề