编程实现循环队列的入队列,计算该队列长度,然后出队列
时间: 2023-12-24 14:45:49 浏览: 31
如何实现循环队列
以下是Python代码实现:
```python
class CircularQueue:
def __init__(self, size):
self.size = size
self.queue = [None] * size
self.front = self.rear = -1
def is_empty(self):
return self.front == -1
def is_full(self):
return (self.rear + 1) % self.size == self.front
def enqueue(self, item):
if self.is_full():
print("Queue is full!")
elif self.is_empty():
self.front = self.rear = 0
self.queue[self.rear] = item
else:
self.rear = (self.rear + 1) % self.size
self.queue[self.rear] = item
def dequeue(self):
if self.is_empty():
print("Queue is empty!")
elif self.front == self.rear:
item = self.queue[self.front]
self.front = self.rear = -1
return item
else:
item = self.queue[self.front]
self.front = (self.front + 1) % self.size
return item
def length(self):
if self.is_empty():
return 0
elif self.front <= self.rear:
return self.rear - self.front + 1
else:
return self.size - self.front + self.rear + 1
# Test the implementation
cq = CircularQueue(5)
cq.enqueue(1)
cq.enqueue(2)
cq.enqueue(3)
cq.enqueue(4)
cq.enqueue(5)
print("Length of queue:", cq.length())
print("Dequeued items:")
print(cq.dequeue())
print(cq.dequeue())
print(cq.dequeue())
print("Length of queue:", cq.length())
```
输出结果:
```
Length of queue: 5
Dequeued items:
1
2
3
Length of queue: 2
```
阅读全文