zoukankan      html  css  js  c++  java
  • 剑指offer:面试题7、用两个栈实现队列

    题目描述

    用两个栈实现队列

    代码示例

    import java.util.Stack;
    
    public class Offer7 {
        public static void main(String[] args) throws Exception{
            Offer7 myQueue = new Offer7();
            myQueue.push(1);
            myQueue.push(2);
            System.out.println(myQueue.pop());//1
            System.out.println(myQueue.pop());//2
        }
    
        Stack<Integer> in = new Stack<>();
        Stack<Integer> out = new Stack<>();
        //入队
        public void push(int node) {
            in.push(node);
        }
        //出队
        public int pop() throws Exception {
            if (out.isEmpty()) {
                while (!in.isEmpty()) {
                    out.push(in.pop());
                }
            }
            if (out.isEmpty()) {
                throw new Exception("queue is empty");
            }
            return out.pop();
        }
    }
    
    
  • 相关阅读:
    [手游新项目历程]-36- error: stray ‘357’ in program
    广告学(一)
    VMware的Unity模式
    poj3709
    poj1849
    bzoj2007
    bzoj3209
    bzoj2466,poj1222
    bzoj1016
    bzoj2186
  • 原文地址:https://www.cnblogs.com/ITxiaolei/p/13138698.html
Copyright © 2011-2022 走看看