编写程序实现顺序栈的初始化、判断栈空否、入栈和出栈
时间: 2023-06-02 12:03:08 浏览: 86
栈的顺序实现,入栈、出栈等
以下是Python语言的实现:
```python
class Stack:
def __init__(self, capacity):
self.capacity = capacity # 栈的容量
self.top = -1 # 栈顶的索引
self.data = [None] * capacity # 存储数据的数组
def is_empty(self):
return self.top == -1
def push(self, value):
if self.top == self.capacity - 1:
print("Stack Overflow")
return
self.top += 1
self.data[self.top] = value
def pop(self):
if self.is_empty():
print("Stack Underflow")
return None
value = self.data[self.top]
self.top -= 1
return value
```
测试代码:
```python
stack = Stack(5)
print(stack.is_empty()) # True
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.pop()) # 3
stack.push(4)
stack.push(5)
stack.push(6) # Stack Overflow
print(stack.pop()) # 5
print(stack.pop()) # 4
print(stack.pop()) # 2
print(stack.pop()) # 1
print(stack.pop()) # Stack Underflow
```
阅读全文