美文网首页
用递归翻转栈

用递归翻转栈

作者: 事件_666 | 来源:发表于2019-05-29 15:34 被阅读0次

    import java.util.Stack;

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

    }

    相关文章

      网友评论

          本文标题:用递归翻转栈

          本文链接:https://www.haomeiwen.com/subject/lfyytctx.html