""" A Queue using a Linked List like structure """from typing import Any, Optionalclass Node:def __init__(self, data: Any, next: Optional["Node"] = None):self.data: Any = dataself.next: Optional["Node"] = nextclass LinkedQueue:"""Linked List Queue implementing put (to end of queue),get (from front of queue) and is_empty>>> queue = LinkedQueue()>>> queue.is_empty()True>>> queue.put(5)>>> queue.put(9)>>> queue.put('python')>>> queue.is_empty();False>>> queue.get()5>>> queue.put('algorithms')>>> queue.get()9>>> queue.get()'python'>>> queue.get()'algorithms'>>> queue.is_empty()True>>> queue.get()Traceback (most recent call last):...IndexError: get from empty queue"""def __init__(self) -> None:self.front: Optional[Node] = Noneself.rear: Optional[Node] = Nonedef is_empty(self) -> bool:""" returns boolean describing if queue is empty """return self.front is Nonedef put(self, item: Any) -> None:""" append item to rear of queue """node: Node = Node(item)if self.is_empty():# the queue contains just the single elementself.front = nodeself.rear = nodeelse:# not empty, so we add it to the rear of the queueassert isinstance(self.rear, Node)self.rear.next = nodeself.rear = nodedef get(self) -> Any:""" returns and removes item at front of queue """if self.is_empty():raise IndexError("get from empty queue")else:# "remove" element by having front point to the next oneassert isinstance(self.front, Node)node: Node = self.frontself.front = node.nextif self.front is None:self.rear = Nonereturn node.data
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。