Question 3:使用递归函数和栈操作逆序一个栈

【题目】:一个栈依次压入1、2、3、4、5,那么从栈顶到栈底分别为5、4、3、2、1。

需要将这个栈转置,从栈顶到栈底为1、2、3、4、5,也就是实现栈中元素的逆序,但是只能用递归函数来实现,不能用其他数据结构。

 

【解答】:

递归函数核心思想:将栈stack的栈底元素返回并移除。

递归方法代码:

/**
 * Reverse Stack without Another Stack
 */
public class ReverseStack {

    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();
        stack.push(3);
        stack.push(5);
        stack.push(9);
        stack.push(6);
        stack.push(1);
        System.out.print(stack.toString());
        reverse(stack);
        System.out.print(stack.toString());
    }

    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 reverse(Stack<Integer> stack) {
        if(stack.isEmpty()) {
            return;
        }
        int i = getAndRemoveLastElement(stack);
        reverse(stack);
        stack.push(i);
    }

}

 

 

  

posted @ 2020-04-16 21:44  灰色飘零  阅读(90)  评论(0)    收藏  举报