zoukankan      html  css  js  c++  java
  • 逆序一个栈,不申请额外空间,只使用递归函数


    import java.util.Stack;

    /**
    * 逆序一个栈,不申请额外空间,只使用递归函数
    */
    public class RevertStack {

    public static void main(String[] args) {
    Stack<Integer> stack = new Stack<>();
    stack.push(1);
    stack.push(2);
    stack.push(3);
    stack.push(4);
    stack.push(5);
    reverse(stack);
    while (!stack.isEmpty()) {
    System.out.println(stack.pop());
    }
    }

    private static void reverse(Stack<Integer> stack) {
    if (stack == null || stack.isEmpty()) {
    return;
    }
    Integer last = getAndRemoveLast(stack);
    reverse(stack);
    stack.push(last);
    }

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

    }

    /* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */
  • 相关阅读:
    JAVA流和File类
    JAVA的Socket
    JAVA反射
    JAVA线程
    JAVA集合
    052-214(新增70题2018)
    052-213(新增70题2018)
    052-212(新增70题2018)
    052-211(新增70题2018)
    052-210(新增70题2018)
  • 原文地址:https://www.cnblogs.com/laydown/p/13664746.html
Copyright © 2011-2022 走看看