输入数据第一行一个整数N为栈中元素的个数。
接下来一行N个整数表示一个栈依次压入的每个元素。
输出一行表示栈中元素逆序后的栈顶到栈底的每个元素
5 1 2 3 4 5
1 2 3 4 5
来一个python能全部跑通的版本
注意: python 的recursion有次数限制, 默认的是1000, 但此处的测试用例的最后一个输入了1500多个数字, 所以要改变默认的限制, 这里保险设置成了2000.
import sys # python has a recurision limitation # default is 1000 sys.setrecursionlimit(2000) def getLastRemove(stack): res = stack.pop() if len(stack) == 0: return res last = getLastRemove(stack) stack.append(res) return last def reverse(stack): if len(stack) == 0: return None i = getLastRemove(stack) reverse(stack) stack.append(i) return None stack = [] N = int(input()) a = input() for i in a.split(): stack.append(int(i)) reverse(stack) s="" for i in range(N): s+= str(stack.pop()) if i < N-1: s+= " " print(s)
# 只用递归函数逆序栈 import sys from collections import deque ''' 栈只能获取顶部,pop, push ''' def get_and_remove_botton_ele(stack:deque)->int: result = stack.pop() if not stack: return result else: last = get_and_remove_botton_ele(stack) stack.append(result) return last def reverse(stack:deque): if not stack: return else: e = get_and_remove_botton_ele(stack) reverse(stack) stack.append(e) n = int(sys.stdin.readline().strip()) x = sys.stdin.readline().strip().split() stack = deque(map(int, x[::-1])) reverse(stack) for i in range(n): print(stack.pop(), end=' ')
import sys from collections import deque def pop_bottom(stack): if len(stack) == 1: return stack.pop() num = stack.pop() res = pop_bottom(stack) stack.append(num) return res def reverse(stack): if stack is None or len(stack) == 0: return num = pop_bottom(stack) reverse(stack) stack.append(num) N = int(sys.stdin.readline().strip()) nums = [int(i) for i in sys.stdin.readline().strip().split()] stack = deque() for num in nums: stack.append(num) reverse(stack) while len(stack) > 0: print(stack.popleft(), end=' ')