1. 程式人生 > >python演算法9.20——棧

python演算法9.20——棧

# 棧是一種線性表,但只允許在一端進行插入、刪除
# 基本原理:
# 1.棧有固定長度,Stack.size
# 2.棧有入棧、出棧操作,push、pop
# 3.入棧時需要考慮棧是否已滿,出棧時需要考慮棧是否為空
# 4.棧有指標,指示棧中元素個數


class Stack():
    def __init__(self,size):
        self.size = size
        self.items = []
        self.top = -1

    def isfull(self):
        return self.top == self.size-1

    def isempty(self):
        return self.top == -1

    def push(self,item):
        if self.isfull():
            raise Exception("Wrong operation! Stack if full!")
        else:
            self.top += 1
            self.items.append(item)

    def pop(self):
        if self.isempty():
            raise Exception("Wrong operation! Stack if empty!")
        else:
            self.top -= 1
            self.items.pop()

    def show(self):
        print(self.items)


if __name__ == '__main__':
    s = Stack(5)
    for i in range(4):
        s.push(i)
        s.show()
    for i in range(2):
        s.pop()
        s.show()