编写程序实现链式存储结构的循环队列,要求用带头结点 和尾指针的循环链表实现,编写函数分别完成队列初始化、入队、出 队、输出队列数据、队列置空、判断队列是否为空的功能。
时间: 2024-12-25 07:29:00 浏览: 1
在Python中,我们可以使用类来实现循环队列,使用一个头节点(front)和尾节点(rear)来指示链表的起始位置。以下是关键部分的实现:
```python
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class CircularQueue:
def __init__(self, capacity):
self.capacity = capacity
self.front = self.rear = -1
self.queue = [None] * capacity
# 初始化队列
def enqueue(self, data):
if (self.rear + 1) % self.capacity == self.front:
print("Queue is full.")
else:
if self.front == -1:
self.front = self.rear = 0
new_node = Node(data)
self.queue[self.rear] = new_node
self.rear = (self.rear + 1) % self.capacity
# 出队操作
def dequeue(self):
if self.is_empty():
print("Queue is empty.")
else:
removed_data = self.queue[self.front]
next_node = self.queue[(self.front + 1) % self.capacity]
self.queue[self.front] = None
if self.front == self.rear:
self.front = self.rear = -1
else:
self.front = (self.front + 1) % self.capacity
return removed_data
# 检查队列是否为空
def is_empty(self):
return self.front == -1 and self.rear == -1
# 输出队列数据
def display(self):
if self.is_empty():
print("Queue is empty.")
else:
current = self.front
while True:
print(self.queue[current], end=" ")
current = (current + 1) % self.capacity
if current == self.front:
break
print()
# 清空队列
def queue_clear(self):
self.front = self.rear = -1
for node in self.queue:
node = None
# 示例
cq = CircularQueue(5)
cq.enqueue(1)
cq.enqueue(2)
cq.enqueue(3)
cq.display() # 输出:1 2 3 (empty spaces)
cq.dequeue()
cq.display() # 输出:2 3 (empty spaces)
print(cq.is_empty()) # 输出:False
cq.queue_clear()
print(cq.is_empty())
阅读全文