1
1
# Implementation of Circular Queue using linked lists
2
2
# https://en.wikipedia.org/wiki/Circular_buffer
3
3
4
+ from __future__ import annotations
5
+
4
6
from typing import Any
5
7
6
8
@@ -18,16 +20,16 @@ class CircularQueueLinkedList:
18
20
"""
19
21
20
22
def __init__ (self , initial_capacity : int = 6 ) -> None :
21
- self .front = None
22
- self .rear = None
23
+ self .front : Node | None = None
24
+ self .rear : Node | None = None
23
25
self .create_linked_list (initial_capacity )
24
26
25
27
def create_linked_list (self , initial_capacity : int ) -> None :
26
28
current_node = Node ()
27
29
self .front = current_node
28
30
self .rear = current_node
29
31
previous_node = current_node
30
- for i in range (1 , initial_capacity ):
32
+ for _ in range (1 , initial_capacity ):
31
33
current_node = Node ()
32
34
previous_node .next = current_node
33
35
current_node .prev = previous_node
@@ -49,9 +51,14 @@ def is_empty(self) -> bool:
49
51
>>> cq.is_empty()
50
52
True
51
53
"""
52
- return self .front == self .rear and self .front .data is None
53
54
54
- def first (self ) -> Any :
55
+ return (
56
+ self .front == self .rear
57
+ and self .front is not None
58
+ and self .front .data is None
59
+ )
60
+
61
+ def first (self ) -> Any | None :
55
62
"""
56
63
Returns the first element of the queue
57
64
>>> cq = CircularQueueLinkedList()
@@ -74,7 +81,7 @@ def first(self) -> Any:
74
81
'b'
75
82
"""
76
83
self .check_can_perform_operation ()
77
- return self .front .data
84
+ return self .front .data if self . front else None
78
85
79
86
def enqueue (self , data : Any ) -> None :
80
87
"""
@@ -92,11 +99,13 @@ def enqueue(self, data: Any) -> None:
92
99
...
93
100
Exception: Empty Queue
94
101
"""
102
+ if self .rear is None :
103
+ return
104
+
95
105
self .check_is_full ()
96
- if self .is_empty ():
97
- self .rear .data = data
98
- else :
106
+ if not self .is_empty ():
99
107
self .rear = self .rear .next
108
+ if self .rear :
100
109
self .rear .data = data
101
110
102
111
def dequeue (self ) -> Any :
@@ -117,6 +126,8 @@ def dequeue(self) -> Any:
117
126
Exception: Empty Queue
118
127
"""
119
128
self .check_can_perform_operation ()
129
+ if self .rear is None or self .front is None :
130
+ return
120
131
if self .front == self .rear :
121
132
data = self .front .data
122
133
self .front .data = None
@@ -133,15 +144,15 @@ def check_can_perform_operation(self) -> None:
133
144
raise Exception ("Empty Queue" )
134
145
135
146
def check_is_full (self ) -> None :
136
- if self .rear .next == self .front :
147
+ if self .rear and self . rear .next == self .front :
137
148
raise Exception ("Full Queue" )
138
149
139
150
140
151
class Node :
141
152
def __init__ (self ) -> None :
142
- self .data = None
143
- self .next = None
144
- self .prev = None
153
+ self .data : Any | None = None
154
+ self .next : Node | None = None
155
+ self .prev : Node | None = None
145
156
146
157
147
158
if __name__ == "__main__" :
0 commit comments