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;
    }
    }

    }

    /* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */
  • 相关阅读:
    【Web】Google Chrome 浏览器调试禁用缓存
    js基础(对象)
    js基础
    css
    html
    mybatis(mapper映射文件)
    mybatis(核心配置文件的配置)
    linux三种连接方式
    spring
    mybatis(入门案例)
  • 原文地址:https://www.cnblogs.com/laydown/p/13664746.html
Copyright © 2011-2022 走看看