用链栈依次进栈数据为 1,2,3,4,5,再全部出栈,输出出栈序列
时间: 2023-08-16 22:07:32 浏览: 117
进栈顺序为1, 2, 3, 4, 5,出栈序列为5, 4, 3, 2, 1。下面是基于链栈的代码实现:
```python
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedStack:
def __init__(self):
self.top = None
def is_empty(self):
return self.top is None
def push(self, data):
node = Node(data)
node.next = self.top
self.top = node
def pop(self):
if self.is_empty():
raise Exception('Stack is empty')
node = self.top
self.top = node.next
return node.data
stack = LinkedStack()
# 进栈
for i in range(1, 6):
stack.push(i)
# 出栈
while not stack.is_empty():
print(stack.pop(), end=' ')
```
输出结果为:5 4 3 2 1。
阅读全文