from 双端链表 import Linklist, Node class MyQueue: def __init__(self, max_num): self.max_num = max_num self.queue = Linklist() def append(self, node): if self.queue.getLength() < self.max_num: self.queue.insert_after(node) else: raise Exception('队列已达最大容量') def pop(self): if not self.isEmpty(): lastNode = self.queue.getTailNode() self.queue.delete(lastNode) return lastNode else: raise Exception('队列已空') def get(self): if not self.isEmpty(): firstNode = self.queue.head if hasattr(self.queue.head, 'next'): self.queue.head.tail = None self.queue.head = self.queue.head.next if self.queue.getLength() != 1: self.queue.head.tail = self.queue.getTailNode() else: self.queue.head = None self.queue.length -= 1 return firstNode else: raise Exception('队列已空') def isEmpty(self): return self.queue.getLength() == 0 def stillTask(self): return self.queue.length myqueue = MyQueue(4) myqueue.append(Node(2)) myqueue.append(Node(4)) myqueue.append(Node(5)) myqueue.append(Node(6)) print(myqueue.stillTask()) print(myqueue.pop().id) print(myqueue.pop().id) print(myqueue.pop().id) print(myqueue.get().id) print(myqueue.get())
python链表实现队列(原创请勿转载)
最新推荐文章于 2024-09-11 18:38:00 发布