题目:
只使用递归跟栈的操作,实现逆序栈
思路:
1.先实现一个栈
class Stack:
def __init__(self):
self.s = []
def push(self, data):
self.s.append(data)
def pop(self):
return self.s.pop()
def empty(self):
return len(self.s) == 0
def dump(self):
print(self.s)
测试:
def test_stack():
stack = Stack()
for i in range(5):
stack.push(i)
stack.dump()
结果:
➜ 3_reverse_stack_using_recursion python reverse_stack_using_recursion.py
[0, 1, 2, 3, 4]
2.递归实现逆序打印栈
def reverse_print(stack):
if stack.empty():
return
a = stack.pop()
reverse_print(stack)
print(a)
测试:
def test_reverse_print():
stack = Stack()
for i in range(5):
stack.push(i)
stack.dump()
reverse_print(stack)
结果:
➜ 3_reverse_stack_using_recursion python reverse_stack_using_recursion.py
[0, 1, 2, 3, 4]
0
1
2
3
4
3.递归实现获取,并移除栈中最底下的元素
跟逆序输出类似:
def get_and_remove_last(stack):
if stack.empty():
raise Exception('Empty stack')
a = stack.pop()
if not stack.empty():
last = get_and_remove_last2(stack)
stack.push(a)
return last
else:
return a
测试:
def test_get_and_remove_last():
stack = Stack()
for i in range(5):
stack.push(i)
stack.dump()
for i in range(5):
last = get_and_remove_last(stack)
print('last:', last)
stack.dump()
结果:
➜ 3_reverse_stack_using_recursion python reverse_stack_using_recursion.py
[0, 1, 2, 3, 4]
last: 0
[1, 2, 3, 4]
last: 1
[2, 3, 4]
last: 2
[3, 4]
last: 3
[4]
last: 4
[]
4.在上面函数的基础上,再加一层递归,就可以实现逆序
def reverse(stack):
if stack.empty():
return
a = get_and_remove_last(stack)
reverse(stack)
stack.push(a)
测试:
def test_reverse():
stack = Stack()
for i in range(5):
stack.push(i)
stack.dump()
reverse(stack)
stack.dump()
结果:
➜ 3_reverse_stack_using_recursion python reverse_stack_using_recursion.py
[0, 1, 2, 3, 4]
[4, 3, 2, 1, 0]