利用系统栈使一个栈逆序

2018-07-17  本文已影响0人  shoulda

题目:

给你一个栈, 请你逆序这个栈, 不能申请额外的数据结构, 只能
使用递归函数。 如何实现?
非常经典的做法

package basic_class_07;

import java.util.Stack;

public class Code_06_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());
        }

    }

}

上一篇 下一篇

猜你喜欢

热点阅读