在TestQueue类里面创建一个链队列,将数字0-9按顺序入队列,并对其进行遍历,输出遍历结果
时间: 2024-05-06 17:20:14 浏览: 54
链队列的实现需要先定义一个节点类,然后在队列类中使用节点类来定义队列节点。以下是一个简单的链队列的实现:
```python
class QueueNode:
def __init__(self, value):
self.value = value
self.next = None
class LinkedQueue:
def __init__(self):
self.head = None
self.tail = None
def is_empty(self):
return self.head is None
def enqueue(self, value):
node = QueueNode(value)
if self.is_empty():
self.head = node
self.tail = node
else:
self.tail.next = node
self.tail = node
def dequeue(self):
if self.is_empty():
raise Exception("Queue is empty")
node = self.head
self.head = node.next
if self.head is None:
self.tail = None
return node.value
def __iter__(self):
node = self.head
while node is not None:
yield node.value
node = node.next
```
然后在TestQueue类中使用该链队列类来创建队列,入队0-9这10个数字,并遍历输出结果:
```python
queue = LinkedQueue()
for i in range(10):
queue.enqueue(i)
for value in queue:
print(value)
```
输出结果为:
```
0
1
2
3
4
5
6
7
8
9
```
阅读全文