-
Notifications
You must be signed in to change notification settings - Fork 1
/
queue_practice.py
46 lines (36 loc) · 997 Bytes
/
queue_practice.py
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
class AbstractQueue:
def __init__(self):
self.top = 0
def __len__(self):
return self.top
def is_empty(self):
return self.top == 0
class QueueNode:
def __init__(self, value):
self.value = value
self.next = None
class LinkedListQueue(AbstractQueue):
def __init__(self):
AbstractQueue.__init__(self)
self.front = None
self.rear = None
def enqueue(self, value):
node = QueueNode(value)
if not self.front:
self.front = node
self.rear = node
else:
self.rear.next = node
self.rear = node
self.top += 1
def dequeue(self):
if self.is_empty():
raise IndexError("Queue is empty")
value = self.front.value
if self.front == self.rear:
self.front = None
self.rear = None
else:
self.front = self.front.next
self.top -= 1
return value