写一个代码建立顺序循环队列并实现出队入队
时间: 2024-10-23 20:19:32 浏览: 29
在Python中,我们可以创建一个基本的顺序循环队列(Circular Queue),它是一个线性结构,数据在两个指针(front 和 rear)之间进行插入和删除操作,当一个端点到达另一个端点时,队列会开始循环。以下是实现顺序循环队列的简单代码:
```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 and self.rear == -1
# 判断队列是否已满
def is_full(self):
if (self.rear + 1) % self.capacity == self.front:
return True
else:
return False
# 入队(enqueue)
def enqueue(self, data):
if self.is_full():
print("Queue is full.")
elif self.is_empty():
self.front = 0
self.rear = 0
else:
self.rear = (self.rear + 1) % self.capacity
self.queue[self.rear] = data
# 出队(dequeue)
def dequeue(self):
if self.is_empty():
print("Queue is empty.")
else:
removed_data = self.queue[self.front]
if self.front == self.rear:
self.front = self.rear = -1
else:
self.front = (self.front + 1) % self.capacity
return removed_data
# 使用示例
cq = CircularQueue(5)
cq.enqueue(1)
cq.enqueue(2)
cq.enqueue(3)
print(cq.dequeue()) # 输出:1
print(cq.dequeue()) # 输出:2
```
阅读全文