栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

用Python实现堆栈

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

用Python实现堆栈

我更正了以下几个问题。同样,用抽象编程术语来说,“堆栈”通常是一个集合,您可以在其中添加或从顶部删除,但是在实现它的方式上,您是在顶部添加并从底部删除,这使其成为一个队列。

class myStack:     def __init__(self):         self.container = []  # You don't want to assign [] to self - when you do that, you're just assigning to a new local variable called `self`.  You want your stack to *have* a list, not *be* a list.     def isEmpty(self):         return self.size() == 0   # While there's nothing wrong with self.container == [], there is a builtin function for that purpose, so we may as well use it.  And while we're at it, it's often nice to use your own internal functions, so behavior is more consistent.     def push(self, item):         self.container.append(item)  # appending to the *container*, not the instance itself.     def pop(self):         return self.container.pop()  # pop from the container, this was fixed from the old version which was wrong     def peek(self):         if self.isEmpty():  raise Exception("Stack empty!")         return self.container[-1]  # View element at top of the stack     def size(self):         return len(self.container)  # length of the container     def show(self):         return self.container  # display the entire stack as lists = myStack()s.push('1')s.push('2')print(s.pop())print(s.show())


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/650063.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号