1.3如何仅用递归函数和栈操作逆序一个栈

版权声明:本文采用 知识共享署名4.0 国际许可协议进行许可。 https://blog.csdn.net/youmian6868/article/details/85273327
题目

仅用递归函数,实现栈中元素的逆序。

代码实现:
/**
 * 将栈stack的栈底元素返回并移除
 *
 * @param stack
 * @return 栈底元素
 */
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;
    }
}

/**
 * 逆序一个栈
 *
 * @param stack
 */
public static void reverse(Stack<Integer> stack) {
    if (stack.isEmpty()) {
        return;
    }
    int i = getAndRemoveLastElement(stack);
    reverse(stack);
    stack.push(i);
}

猜你喜欢

转载自blog.csdn.net/youmian6868/article/details/85273327