顺序栈的基本模型
完整代码
点击查看代码
#! /usr/bin/env python3
class Stack:
# stack: initiate, is_empty, is_full, push and pop
def __init__(self, maxsize):
self.data = [0 for i in range(maxsize)]
self.top = -1
self.maxsize = maxsize
def is_empty(self):
return self.top == -1
def is_full(self):
return self.top == self.maxsize - 1
def push(self, element):
if self.is_full():
print("Ths stack is full!")
return False
else:
self.top += 1
self.data[self.top] = element
return True
def pop(self):
if self.is_empty():
print("The stack is empyt!")
return -9999
else:
popped_value = self.data[self.top]
self.top -= 1
return popped_value
def main():
# use while loop to perform push and pop operation
stack = Stack(int(input("input maxsize: ")))
while True:
message = input("push/pop/exit: ")
if message == 'exit':
break
elif message == 'push':
stack.push(int(input("Value Pushed: ")))
elif message == 'pop':
print("Poped Value:", stack.pop())
else:
print("Plese input 'push', 'pop' or 'exit'")
print(f"stack.data = {stack.data}")
print(f"stack.top = {stack.top}")
if __name__ == '__main__':
main()