Links: https://www.nowcoder.com/questionTerminal/ba7d7f5d1edf4d1690d66e12e951f6ea
Source: niuke.com
Title:
If a stack is pressed in 1,2,3,4,5, then the stack top to the bottom are 5,4,3,2,1 respectively. After the stack is transposed, it is 1,2,3,4,5 from the top of the stack to the bottom of the stack, that is to say, the reverse order of the elements in the stack is realized. Please design an algorithm to realize the operation of the reverse order stack, but it can only be realized by recursive functions, not by other data structures. Given a Stack and the Stack size top, please return the Stack in reverse order. Test example: [1,2,3,4,5],5 Return: [5,4,3,2,1]
Train of thought:
Answer:
import java.util.Stack; /** * Only use recursion function and stack to reverse a stack: ReverseStack [2] * * [Press 1, 2, and 3 into a stack in turn, and transpose the stack so that the top to bottom of the stack is 1, 2, and 3 in turn. Only recursive functions can be used, and additional data structures, including stacks, cannot be borrowed] * * Algorithm idea: two recursive functions (getAndRemoveBottom, reverse) * * @Author: zyx * @Date: 2019/4/25 16:24 * @Description: */ public class ReverseStack { public int[] reverseStackRecursively(int[] stack, int top) { // write code here if (stack == null || stack.length == 0) { return null; } Stack<Integer> s = new Stack<Integer>(); for (int i = 0; i <= top - 1; i++) { s.push(stack[i]); } reverse(s); for (int i = top - 1; i >= 0; i--) { stack[i] = s.pop(); } return stack; } /** * Each layer recursively extracts the elements at the bottom of the stack and caches them in variables until the stack is empty; * * Then, the variables of each layer are pushed into the stack reversely, and finally the data of the original stack is reversed. * * @param stack */ public static void reverse(Stack<Integer> stack) { if (stack.empty()) { return; } int i = getAndRemoveBottom(stack);// Return to 1, 2 and 3 in turn reverse(stack); stack.push(i);// Press in 3, 2 and 1 successively } /** * Return and remove the current stack bottom element (the stack elements < stack bottom > 1, 2, 3 < stack top > change to 2, 3 < stack top >) */ public static int getAndRemoveBottom(Stack<Integer> stack) { int result = stack.pop(); if (stack.empty()) { return result; } else { int Bottom = getAndRemoveBottom(stack); stack.push(result); return Bottom;// In the first round, return the stack bottom element 1 } } }