用python实现栈_用Python实现堆栈

我纠正了下面的几个问题。另外,抽象编程术语中的“stack”通常是一个集合,您可以在上面添加和从上面删除,但是您实现它的方式是,从上面添加和从下面删除,这使它成为一个队列。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 list

s = myStack()

s.push('1')

s.push('2')

print(s.pop())

print(s.show())

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值