题目:给你一个栈,请你逆序这个栈
package Algorithms.ViolenceRecursive; import java.util.Stack; public class ReverseStackUsingRecursive { //逆序栈 public static void reverse(Stack<Integer> stack) { if (stack.isEmpty()) { return; } int i = getAndRemoveLastElement(stack); reverse(stack); stack.push(i); } //移除栈底元素并返回 public static int getAndRemoveLastElement(Stack<Integer> stack) { int result = stack.pop(); if (stack.isEmpty()) { return result; } else { int last = getAndRemoveLastElement(stack); stack.push(result); return last; } } public static void main(String[] args) { Stack<Integer> test = new Stack<Integer>(); test.push(1); test.push(2); test.push(3); test.push(4); test.push(5); reverse(test); while (!test.isEmpty()) { System.out.println(test.pop()); } } }
过程解析:
public static int getAndRemoveLastElement(Stack<Integer> stack) { // 1 2 3 int result = stack.pop(); //(1)弹1 if (stack.isEmpty()) { return result; } else { int last = getAndRemoveLastElement(stack); { int result = stack.pop(); //(2) 弹2 if (stack.isEmpty()) { return result; } else { int last = getAndRemoveLastElement(stack); { int result = stack.pop(); //(3) 弹3 if (stack.isEmpty()) { return result; //(4)返回3 } else { int last = getAndRemoveLastElement(stack); stack.push(result); return last; } } stack.push(result); //(5) 压2 return last; //(6) 返回3 } } stack.push(result); //(7)压1 return last; (8)//返回3 } }
逆序栈:
public static void reverse(Stack<Integer> stack) { //1 2 3 if (stack.isEmpty()) { return; } int i = getAndRemoveLastElement(stack); // (1)i = 3 栈中剩余:1 2 reverse(stack); { if (stack.isEmpty()) { return; } int i = getAndRemoveLastElement(stack); //(2)i = 2 栈中剩余:1 reverse(stack); { if (stack.isEmpty()) { return; } int i = getAndRemoveLastElement(stack);//(3) i = 1 栈空 reverse(stack); // (4)栈空,递归结束 stack.push(i); //(5)压1 } stack.push(i); //(6)压2 } stack.push(i); //(7)压3 }