只使用递归和栈操作实现栈的逆序
#!/usr/bin/env python # --*-- coding: utf-8 --*-- def popbottom(s): x = s.pop() if not s: return x else: bottom = popbottom(s) s.append(x) return bottom def reverse(s): if not s: return x = popbottom(s) if not s: s.append(x) else: reverse(s) s.append(x) if __name__ == ‘__main__‘: s = [1, 2, 3, 4, 5, 6] print(‘逆序前:‘) print(s) reverse(s) print(‘逆序后:‘) print(s)
时间: 2024-10-12 08:54:33