编写一个程序模拟堆栈,要求能够模拟、入栈、出栈、返回栈顶元素等基本操作。栈中元素可用整数代替。不能使用C++模板库预定义的类型。程序运行中可输入多组入栈、出栈操作,每次操作后展示栈中元素。
时间: 2023-12-20 08:04:30 浏览: 36
好的,我能够帮你编写一个符合要求的堆栈程序。以下是 Python 代码实现:
```python
class Stack:
def __init__(self):
self.stack = []
def push(self, item):
self.stack.append(item)
def pop(self):
if not self.is_empty():
return self.stack.pop()
else:
return None
def peek(self):
if not self.is_empty():
return self.stack[-1]
else:
return None
def is_empty(self):
return len(self.stack) == 0
def print_stack(self):
print("Stack: ", end="")
for item in self.stack:
print(item, end=" ")
print()
if __name__ == "__main__":
my_stack = Stack()
while True:
print("Please input your operation (push/pop/peek/print/quit):")
op = input().strip()
if op == "push":
print("Please input the number you want to push:")
num = int(input().strip())
my_stack.push(num)
my_stack.print_stack()
elif op == "pop":
num = my_stack.pop()
if num is not None:
print("Pop number:", num)
my_stack.print_stack()
elif op == "peek":
num = my_stack.peek()
if num is not None:
print("Peek number:", num)
my_stack.print_stack()
elif op == "print":
my_stack.print_stack()
elif op == "quit":
break
else:
print("Invalid operation!")
```
这个堆栈程序实现了基本的入栈、出栈、返回栈顶元素和展示栈中元素的操作。当程序运行时,每次输入一个操作指令,程序会相应地进行操作并展示当前栈中的元素。如果输入 quit,则程序会结束。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)