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());
    }
    }
    }
     
  • 相关阅读:
    再回首Java第九天
    再回首Java第八天
    再回首Java一周记
    再回首Java第六天
    再回首Java第五天
    再回首Java第四天
    再回首Java第三天
    再回首Java第二天
    再回首Java第一天
    关于i++和++i理解
  • 原文地址:https://www.cnblogs.com/xuhaojun/p/9108746.html
Copyright © 2011-2022 走看看