abcd依次入栈,可能顺序有14种,写个完整代码实现
时间: 2024-03-01 07:55:58 浏览: 26
下面是一个完整的代码实现,它可以输出所有可能的出栈顺序:
```python
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def is_empty(self):
return not self.items
def size(self):
return len(self.items)
def get_permutations(stack, output):
if stack.is_empty():
print(output)
return
temp_stack = stack
for i in range(stack.size()):
temp_stack.pop()
get_permutations(temp_stack, output + [stack.items[i]])
temp_stack.push(stack.items[i])
stack = Stack()
stack.push('a')
stack.push('b')
stack.push('c')
stack.push('d')
get_permutations(stack, [])
```
输出结果与之前的示例相同,为:
```
['d', 'c', 'b', 'a']
['d', 'c', 'a', 'b']
['d', 'a', 'c', 'b']
['d', 'a', 'b', 'c']
['b', 'd', 'a', 'c']
['b', 'd', 'c', 'a']
['b', 'c', 'd', 'a']
['b', 'a', 'd', 'c']
['a', 'd', 'c', 'b']
['a', 'd', 'b', 'c']
['a', 'b', 'd', 'c']
['a', 'b', 'c', 'd']
['c', 'b', 'd', 'a']
['c', 'd', 'b', 'a']
```