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()

猜你喜欢

转载自blog.csdn.net/nominior/article/details/82793947