编写程序实现顺序栈的初始化、判断栈空否、入栈和出栈等
时间: 2023-05-29 14:03:09 浏览: 76
操作,具体实现如下:
```python
class Stack:
def __init__(self, capacity=10):
self.capacity = capacity # 栈的容量
self.top = -1 # 栈顶指针,初始值为-1
self.data = [None] * capacity # 存储元素的列表
def is_empty(self):
"""判断栈是否为空"""
return self.top == -1
def push(self, value):
"""入栈操作"""
if self.top == self.capacity - 1:
raise Exception('Stack Overflow')
self.top += 1
self.data[self.top] = value
def pop(self):
"""出栈操作"""
if self.top == -1:
raise Exception('Stack Underflow')
value = self.data[self.top]
self.top -= 1
return value
```
测试代码:
```python
s = Stack(5)
print(s.is_empty()) # True
s.push(1)
s.push(2)
s.push(3)
print(s.pop()) # 3
s.push(4)
s.push(5)
print(s.pop()) # 5
print(s.pop()) # 4
print(s.pop()) # 2
print(s.pop()) # 1
print(s.is_empty()) # True
```
输出结果:
```
True
3
5
4
2
1
True
```
阅读全文