python写算法中的栈

###########  栈的使用  ###############

class StackFullError(Exception):
    pass
class StackEmptyError(Exception):
    pass

class Stack(object):
    def __init__(self,size):
        self.size=size
        self.lst = []
        self.top = 0

    def push(self,item):
        if self.top == self.size:
            raise StackFullError("超出异常")
        # self.lst[self.top] = item   # 一开始是没有索引0的,会报错
        self.lst.insert(self.top,item)   # 可以使用insert,根据索引进行插入值
        self.top += 1

    def pop(self):
        if self.top == 0:
            raise StackEmptyError("没有了")
        self.top -= 1
        item = self.lst[self.top]   # 获取元素
        return item

s = Stack(5)
s.push("chen1")
s.push("chen2")
s.push("chen3")
s.push("chen4")
s.push("chen5")

print(s.pop())
print(s.pop())
print(s.pop())
print(s.pop())
print(s.pop())

 

posted @ 2019-03-12 16:17  葡萄想柠檬  Views(238)  Comments(0Edit  收藏  举报
目录代码