编写程序实现循环队列的初始化、判断队列空否、入队列和出队列等
时间: 2024-01-27 19:05:45 浏览: 130
数据结构与算法C++实现 循环顺序队列的初始化,求长度,入队,出队
5星 · 资源好评率100%
操作。
```python
class CircularQueue:
def __init__(self, capacity):
self.capacity = capacity
self.queue = [None] * capacity
self.front = -1
self.rear = -1
def is_empty(self):
return self.front == -1
def is_full(self):
if self.front == 0 and self.rear == self.capacity - 1:
return True
if self.front == self.rear + 1:
return True
return False
def enqueue(self, data):
if self.is_full():
print("Queue is full.")
return
if self.front == -1:
self.front = 0
self.rear = (self.rear + 1) % self.capacity
self.queue[self.rear] = data
def dequeue(self):
if self.is_empty():
print("Queue is empty.")
return
data = self.queue[self.front]
self.queue[self.front] = None
if self.front == self.rear:
self.front = -1
self.rear = -1
else:
self.front = (self.front + 1) % self.capacity
return data
```
使用示例:
```python
queue = CircularQueue(5)
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
queue.enqueue(4)
queue.enqueue(5)
queue.enqueue(6) # Queue is full.
print(queue.dequeue()) # 1
print(queue.dequeue()) # 2
queue.enqueue(6)
queue.enqueue(7)
print(queue.dequeue()) # 3
print(queue.dequeue()) # 4
print(queue.dequeue()) # 5
print(queue.dequeue()) # 6
print(queue.dequeue()) # 7
queue.dequeue() # Queue is empty.
```
阅读全文