# Implementation of the Stack ADT using a singly linked list.class Stack:# Creates an empty stackdef __init__(self):self._top = Noneself._size = 0# Returns True if the stack is empty or False otherwise.def isEmpty(self):return self._top is None# Returns the number of items in the stack.def __len__(self):return self._size# Returns the top item on the stack without removing it.def peek(self):assert not self.isEmpty(), "Cannot peek at an empty stack"return self._top.item# Removes and returns the top item on the stack.def pop(self):assert not self.isEmpty(), "Cannot pop from an empty stack"node = self._topself._top = self._top.nextself._size -= 1return node.item# Pushes an item onto the top of the stack.def push(self, item):self._top = _StackNode(item, self._top)self._size += 1class _StackNode:def __init__(self, item, link):self.item = itemself.next = link
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。