pycharm用顺序存储实现栈的初始化、入栈、出栈、销毁栈操作
时间: 2023-05-12 22:06:19 浏览: 102
非常感谢您的提问!以下是使用顺序存储实现栈的初始化、入栈、出栈、销毁栈操作的代码:
```python
class Stack:
def __init__(self, size):
self.size = size
self.stack = [None] * size
self.top = -1
def push(self, data):
if self.top == self.size - 1:
print("Stack Overflow!")
return
self.top += 1
self.stack[self.top] = data
def pop(self):
if self.top == -1:
print("Stack Underflow!")
return None
data = self.stack[self.top]
self.top -= 1
return data
def destroy(self):
self.top = -1
self.stack = None
```
使用方法如下:
```python
stack = Stack(5)
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.pop()) # 输出 3
stack.destroy()
```
希望这个代码能够帮助到您!
阅读全文