帮我写一个,判断栈进出顺序是否正确的编程题
时间: 2023-05-31 07:02:37 浏览: 74
以下是一个 Python 的实现,思路是利用一个辅助栈模拟栈的进出过程,如果最终辅助栈为空,说明进出顺序正确,否则不正确。
```python
def check_stack_order(stack, order):
"""
判断栈的进出顺序是否正确
:param stack: 栈
:param order: 进出顺序
:return: 进出顺序是否正确
"""
if not stack or not order:
return False
helper = []
for x in order:
if stack and stack[-1] == x:
stack.pop()
elif helper and helper[-1] == x:
helper.pop()
else:
while stack and stack[-1] != x:
helper.append(stack.pop())
if not stack:
return False
stack.pop()
while stack and helper:
if stack.pop() != helper.pop():
return False
return True
```
示例:
```python
stack = [1, 2, 3, 4, 5]
order1 = [4, 5, 3, 2, 1]
order2 = [4, 3, 5, 1, 2]
print(check_stack_order(stack, order1)) # True
print(check_stack_order(stack, order2)) # False
```
阅读全文