循环链式队列python
时间: 2024-10-17 08:02:16 浏览: 33
python/golang实现循环链表的示例代码
循环链式队列是一种特殊的线性数据结构,它将链表的头结点指向尾节点,形成一个闭环,这样可以避免在队列满时需要频繁移动元素的问题。在Python中,我们可以手动实现一个简单的循环链式队列,例如:
```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 = None
def is_empty(self):
return self.front is None
def is_full(self):
return (self.rear + 1) % self.capacity == self.front
def enqueue(self, item):
if self.is_full():
print("Queue is full.")
return
new_node = Node(item)
if self.is_empty():
self.front = self.rear = new_node
else:
self.rear.next = new_node
self.rear = new_node
self.rear.next = self.front
def dequeue(self):
if self.is_empty():
print("Queue is empty.")
return
removed_data = self.front.data
if self.front == self.rear:
self.front = self.rear = None
else:
self.front = self.front.next
return removed_data
# 使用示例
queue = CircularQueue(5)
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
print(queue.dequeue()) # 输出: 1
print(queue.dequeue()) # 输出: 2
```
阅读全文