帮我写一个实现顺序栈的代码
时间: 2023-05-29 17:02:42 浏览: 93
下面是 Python 的实现:
```python
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.pop()
def is_empty(self):
return len(self.items) == 0
def peek(self):
if not self.is_empty():
return self.items[-1]
def size(self):
return len(self.items)
```
使用方式:
```python
stack = Stack()
stack.push(1) # 入栈
stack.push(2)
stack.push(3)
print(stack.pop()) # 3,出栈
print(stack.peek()) # 2,查看栈顶元素
print(stack.size()) # 2,查看栈大小
```
阅读全文