不用new一个容器将一个栈的顺序反转

import java.util.Stack;

public class Test {
    public static void main(String[] args) {
        Stack<Integer> integers = new Stack<>();
        integers.push(1);
        integers.push(2);
        integers.push(3);
        integers.push(4);
        reverse(integers);
        System.out.println("integers = " + integers);
    }

    private static int f(Stack<Integer> stack){
        int result = stack.pop();
        if(stack.isEmpty()){
            return result;
        }else{
            int last = f(stack);
            stack.push(result);
            return last;
        }
    }

    private static void reverse(Stack<Integer> stack){
        if(stack.isEmpty()){
            return;
        }
        int i = f(stack);
        reverse(stack);
        stack.push(i);
    }
}

复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享