-
Notifications
You must be signed in to change notification settings - Fork 43
/
queue2.py
121 lines (104 loc) · 3.27 KB
/
queue2.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
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
119
120
121
#---------------------------------------------------------------
# QUEUE (V2)
#---------------------------------------------------------------
# V0
class Queue(object):
def __init__(self, limit = 10):
self.queue = []
self.front = None
self.rear = None
self.limit = limit
self.size = 0
def __str__(self):
return ' '.join([str(i) for i in self.queue])
# to check if queue is empty
def isEmpty(self):
return self.size <= 0
# to add an element from the rear end of the queue
def enqueue(self, data):
if self.size >= self.limit:
return -1 # queue overflow
else:
"""
BEWARE OF IT
-> the queue is in "inverse" order to the array which is the way we implement here in python
i.e.
q = [1,2,3]
but the q is start from 1, end at 3 actually
e.g.
dequeue <---- 1, 2 ,3 <---- enqueue
"""
self.queue.append(data)
# assign the rear as size of the queue and front as 0
if self.front is None:
self.front = self.rear = 0
else:
self.rear = self.size
self.size += 1
# to pop an element from the front end of the queue
def dequeue(self):
if self.isEmpty():
return -1 # queue underflow
else:
"""
BEWARE OF IT
x = [1,2,3]
x.pop(0)
-> x = [2,3]
"""
self.queue.pop(0)
self.size -= 1
if self.size == 0:
self.front = self.rear = 0
else:
self.rear = self.size - 1
def getSize(self):
return self.size
# V1
# https://github.com/yennanliu/Data-Structures-using-Python/blob/master/Queue/Queue.py
class Queue(object):
def __init__(self, limit = 10):
self.queue = []
self.front = None
self.rear = None
self.limit = limit
self.size = 0
def __str__(self):
return ' '.join([str(i) for i in self.queue])
# to check if queue is empty
def isEmpty(self):
return self.size <= 0
# to add an element from the rear end of the queue
def enqueue(self, data):
if self.size >= self.limit:
return -1 # queue overflow
else:
self.queue.append(data)
# assign the rear as size of the queue and front as 0
if self.front is None:
self.front = self.rear = 0
else:
self.rear = self.size
self.size += 1
# to pop an element from the front end of the queue
def dequeue(self):
if self.isEmpty():
return -1 # queue underflow
else:
self.queue.pop(0)
self.size -= 1
if self.size == 0:
self.front = self.rear = 0
else:
self.rear = self.size - 1
def getSize(self):
return self.size
# if __name__ == '__main__':
# myQueue = Queue()
# for i in range(10):
# myQueue.enqueue(i)
# print(myQueue)
# print(('Queue Size:',myQueue.getSize()))
# myQueue.dequeue()
# print(myQueue)
# print(('Queue Size:',myQueue.getSize()))