本题要求实现一个普通顺序队列。 当输入1 2 3 -1时,输出为1 2 3 。 当输入为1 2 3 4 5 6 7 8 9 10 11 -1时,输出为 queue is full! 1 2 3 4 5 6 7 8 9 10
时间: 2024-01-09 21:04:52 浏览: 110
输入10个数,然后按顺序排列
以下是普通顺序队列的实现代码:
```python
class Queue:
def __init__(self, capacity):
self.capacity = capacity
self.front = 0
self.rear = 0
self.data = [None] * self.capacity
def enqueue(self, item):
if self.rear == self.capacity:
print("queue is full!")
return False
else:
self.data[self.rear] = item
self.rear += 1
return True
def dequeue(self):
if self.front == self.rear:
print("queue is empty!")
return None
else:
item = self.data[self.front]
self.data[self.front] = None
self.front += 1
return item
def size(self):
return self.rear - self.front
def is_empty(self):
return self.rear == self.front
def is_full(self):
return self.rear == self.capacity
def test_queue(inputs):
queue = Queue(3)
for item in inputs:
if item == -1:
break
else:
result = queue.enqueue(item)
if not result:
break
while not queue.is_empty():
result = queue.dequeue()
print(result, end=' ')
test_queue([1, 2, 3, -1]) # expect output: 1 2 3
test_queue([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, -1]) # expect output: queue is full! 1 2 3 4 5 6 7 8 9 10
```
注意到第二个测试用例的输出结果,当队列满的时候,我们需要给出提示并停止入队操作。
阅读全文