剑指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();
    }
}

posted @ 2020-06-16 00:12  IT小磊  阅读(40)  评论(0编辑  收藏  举报