zoukankan      html  css  js  c++  java
  • 剑指offer 5.用两个栈实现队列

    5.用两个栈实现队列

    题目

    用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

    思路

    栈是先进后出,队列是先进先出,两个栈,那么负负得正,就可以得到先进先出。
    入栈就直接使用第一个栈,栈内关系有序,出栈时,若第二个栈为空,就将第一个栈转移到第二个栈,先进第一个栈后出第一个栈后进第二个栈,先出第一个栈,方向调过来了。若第二个栈不为空,那就输出第二个栈的顶端,顺序一样的。

    代码

      Stack<Integer> stack1 = new Stack<Integer>();
      Stack<Integer> stack2 = new Stack<Integer>();
    
      public void push(int node) {
        stack1.push(node);
      }
    
      public int pop() {
        if (stack2.empty()) {
          while (!stack1.empty()) {
            int temp = stack1.pop();
            stack2.push(temp);
          }
        }
        int temp = stack2.peek();
        stack2.pop();
        return temp;
      }
    
  • 相关阅读:
    去除字符串中多余空格
    day02-03 字符编码
    eclipse与myeclipse区别
    xz解压和zip解压
    yum安装
    防火墙
    查看和操作HBA卡
    复制linux虚拟机后网卡不能用的解决方法
    关闭IPv6
    更改root密码
  • 原文地址:https://www.cnblogs.com/blogxjc/p/12367172.html
Copyright © 2011-2022 走看看