225. 用队列实现栈

2019-02-18  本文已影响0人  上杉丶零
class MyStack {
    private Queue<Integer> queuePush;
    private Queue<Integer> queuePop;

    public MyStack() {
        queuePush = new LinkedList<Integer>();
        queuePop = new LinkedList<Integer>();
    }

    public void push(int x) {
        queuePush.add(x);
    }

    public int pop() {
        int length = queuePush.size();

        for (int i = 0; i < length - 1; i++) {
            queuePop.add(queuePush.poll());
        }

        int value = queuePush.poll();
        queuePush.addAll(queuePop);
        queuePop.clear();
        return value;
    }

    public int top() {
        int length = queuePush.size();

        for (int i = 0; i < length - 1; i++) {
            queuePop.add(queuePush.poll());
        }

        int value = queuePush.poll();
        queuePop.add(value);
        queuePush.addAll(queuePop);
        queuePop.clear();
        return value;
    }

    public boolean empty() {
        return queuePush.isEmpty();
    }
}
image.png
上一篇下一篇

猜你喜欢

热点阅读