分析
代码
class Queue:
def __init__(self,size):
self.items = [None]*size
self.size =size
self.head = 0
self._length = 0
def is_empty(self):
return self._length ==0
def length(self):
return self._length
def push(self, item):
if self.length() == self.size:
raise ValueError("队列已满")
else:
idx = (self.head + self.length()) % self.size
self.items[idx] = item
self._length += 1
def pop(self):
if self.is_empty():
raise ValueError("队列为空")
else:
value = self.items[self.head]
self.head = (self.head +1) % self.size
self._length -= 1
return value
def peek(self):
if self.is_empty():
raise ValueError("队列为空")
return self.items[self.head]
if __name__ == "__main__":
queue = Queue(3)
queue.push(1)
queue.push(2)
queue.push(3)
print(queue.pop())
queue.push(4)
print(queue.length())
print(queue.peek())
print(queue.pop())
print(queue.pop())
print(queue.pop())
print(queue.items)
- 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
结果