Skip to content

Commit b995b7a

Browse files
committed
committed from zkp
1 parent 9cd2ae7 commit b995b7a

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

LeetCode/ArrayQueue.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
class Array:
2+
def __init__(self, size=32):
3+
self._size = size
4+
self._items = [None]*32
5+
def __getitem__(self, index):
6+
return self._items[index]
7+
def __setitem__(self, index, value):
8+
self._items[index] = value
9+
def __len__(self):
10+
return self._size
11+
def clear(self, value=None):
12+
for i in range(len(self._items)):
13+
self._items[i] = value
14+
def __iter__(self):
15+
for i in self._items:
16+
yield i
17+
class FullError(Exception):
18+
pass
19+
class ArrayQueue:
20+
'''定长的队列,当队列满了之后再添加元素,会覆盖掉最后添加的一个元素。'''
21+
def __init__(self, maxsize):
22+
self.maxsize = maxsize
23+
self.array = Array(maxsize)
24+
self.head = 0
25+
self.tail = 0
26+
def push(self, value):
27+
if len(self.array) > self.maxsize:
28+
raise FullError('The queue is full')
29+
self.array[self.head%self.maxsize] = value
30+
self.head += 1
31+
def pop(self):
32+
value = self.array[self.tail%self.maxsize]
33+
self.tail += 1
34+
return value
35+
def __len__(self):
36+
return self.head - self.tail
37+
def test_array_queue():
38+
size = 5
39+
q = ArrayQueue(size)
40+
for i in range(size):
41+
q.push(i)
42+
assert len(q) == size
43+
assert q.pop() == 0
44+
assert q.pop() == 1
45+
q.push(5)
46+
assert len(q) == 4
47+
assert q.pop() == 2
48+
assert q.pop() == 3
49+
assert q.pop() == 4
50+
assert q.pop() == 5
51+
assert len(q) == 0
52+
print('Test Successful')
53+
if __name__ == "__main__":
54+
test_array_queue()

0 commit comments

Comments
 (0)