链式存储结构实现队列
时间: 2023-12-24 13:25:24 浏览: 97
队列的链表存储结构及实现(建立,入队一个元素,出队一个元素)
5星 · 资源好评率100%
链式存储结构实现队列,即使用链表来存储队列中的元素。队列的头部和尾部分别对应链表的头结点和尾结点,入队操作相当于在链表尾部插入一个新结点,出队操作相当于删除链表头部的结点。下面是链式存储结构实现队列的具体实现方法:
1.定义队列结点类
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
```
2.定义队列类
```python
class Queue:
def __init__(self):
self.head = None
self.tail = None
def is_empty(self):
return self.head is None
def enqueue(self, data):
new_node = Node(data)
if self.is_empty():
self.head = new_node
self.tail = new_node
else:
self.tail.next = new_node
self.tail = new_node
def dequeue(self):
if self.is_empty():
raise Exception("Queue is empty")
else:
data = self.head.data
self.head = self.head.next
if self.head is None:
self.tail = None
return data
def size(self):
count = 0
current = self.head
while current is not None:
count += 1
current = current.next
return count
```
3.测试代码
```python
q = Queue()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
print(q.dequeue()) # 输出:1
print(q.dequeue()) # 输出:2
print(q.size()) # 输出:1
```
阅读全文