zoukankan      html  css  js  c++  java
  • 逆序一个栈

    如何不使用额外的栈来逆序一个栈?

    
    
    import java.util.Stack;

    public class StackReverse {
    //翻转栈
    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);
    //在得到 last 后,会从当前的result逐步递归回第一个result
    //需要执行完完整的方法,所以不是只压入一个result,压入的result的个数是stack中元素的个数减1
    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());
    }
    }
    }
     
  • 相关阅读:
    VIM 文本对象选择
    XLA优化实例
    TVM/Relay 的 PartitionGraph()(mod) 函数讨论整理
    OpenCL通用异构开放环境
    LLVM IR 理解
    vue——请求跨域时,vcli2/vcli3设置代理
    【转】SQL 21天实战练习
    bash命令
    linux命令
    jenkins技术
  • 原文地址:https://www.cnblogs.com/xuhaojun/p/9108746.html
Copyright © 2011-2022 走看看