数据结构链表之队列
队列概述
- 定义:队列是一种基于先进先出(FIFO)的数据结构,队列只能在一段进行插入和删除操作的结构,第一个进入队列的元素在读取时会第一个被读取
队列可以使用顺序表(Python中列表)实现,也可以用链表实现,这里介绍链表实现的方法
主要实现以下几个功能:
- is_empty()判断是否队列为空
- size()查看队列长度
- enqueue()向队列插入元素
- dequeue()从队列的头部取出一个元素
- 重写__iter__()和__next__()实现遍历功能
Python代码实现
class Node:def __init__(self, item):"""Define linked list node"""self.item = itemself.next = Noneclass Queue:def __init__(self):self.head = Noneself.last = Noneself.len = 0def is_empty(self):return self.len == 0def size(self):return self.lendef enqueue(self, item):"""Enqueue an element into this queue"""node = Node(item)if not self.last:self.head = nodeelse:self.last.next = nodeself.last = nodeself.len += 1def dequeue(self):"""Dequeue an element from this queue"""if self.head != self.last:# Has at least two elementsres = self.headself.head = self.head.nextself.len -= 1return res# Has one or zero elementres = self.headself.head = Noneself.last = Noneself.len -= 1return resdef __iter__(self):self.cur = self.headreturn selfdef __next__(self):try:temp = self.curself.cur = self.cur.nextreturn tempexcept AttributeError as e:raise StopIteration
功能验证
if __name__ == '__main__':queue = Queue()print(f"Is empty? {queue.is_empty()}")queue.enqueue(1)queue.enqueue(2)queue.enqueue(3)queue.enqueue(4)print(f"Show all elements in this queue: {[i.item for i in queue]}")print(f"Length of this queue: {queue.len}")print(f"Dequeue an element, its value: {queue.dequeue().item}")print(f"After dequeuing an element, length of this queue: {queue.len}")
打印结果:
Is empty? True
Show all elements in this queue: [1, 2, 3, 4]
Length of this queue: 4
Dequeue an element, its value: 1
After dequeuing an element, the length of this queue: 3