1. 建立顺序栈,并在顺序栈上实现入栈和出栈操作(验证性内容)。
时间: 2024-02-03 10:12:46 浏览: 79
栈的创建,入栈,出栈
5星 · 资源好评率100%
好,以下是使用 Python 语言实现顺序栈的示例代码:
```python
class Stack:
def __init__(self, size):
self.size = size
self.stack = []
def push(self, item):
if len(self.stack) == self.size:
print("Stack is full!")
else:
self.stack.append(item)
print(f"{item} is pushed into the stack.")
def pop(self):
if not self.stack:
print("Stack is empty!")
else:
item = self.stack.pop()
print(f"{item} is popped from the stack.")
def display(self):
if not self.stack:
print("Stack is empty!")
else:
print("Current stack:")
for item in reversed(self.stack):
print(item)
# 测试代码
if __name__ == '__main__':
s = Stack(5)
s.push(1)
s.push(2)
s.push(3)
s.display()
s.pop()
s.display()
s.pop()
s.pop()
s.pop()
```
运行结果如下:
```
1 is pushed into the stack.
2 is pushed into the stack.
3 is pushed into the stack.
Current stack:
3
2
1
3 is popped from the stack.
Current stack:
2
1
2 is popped from the stack.
1 is popped from the stack.
Stack is empty!
```
阅读全文