程序员代码面试

【算法题】如何仅用递归函数逆序一个栈

2018-12-02  本文已影响0人  埋没随百草

一个栈依次压入1、2、3、4、5,那么从栈顶到栈底分别是5、4、3、2、1。要求只用递归,不借助其他数据结构,实现栈的逆序,即从栈顶到栈底变为1、2、3、4、5。

解题思路

对于递归操作,通常都是由极端情况推广到一般情况。

对于"获取并移除栈底元素",我们同样用以递归来实现:

实现代码

public class ReverseStack {
    public static void reverse(Stack<Integer> stack) {
        if (stack.empty()) {
            return;
        }

        int bottom = getAndRemoveBottomElement(stack);
        reverse(stack);
        stack.push(bottom);
    }

    public static int getAndRemoveBottomElement(Stack<Integer> stack) {
        int result = stack.pop();
        if (stack.empty()) {
            return result;
        } else {
            int bottom = getAndRemoveBottomElement(stack);
            stack.push(result);
            return bottom;
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读