[Stack]225. Implement Stack using Queues

Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push, top, pop, and empty).

Implement the MyStack class:

void push(int x) Pushes element x to the top of the stack.

int pop() Removes the element on the top of the stack and returns it.

int top() Returns the element on the top of the stack.

boolean empty() Returns true if the stack is empty, false otherwise.

Notes:

You must use only standard operations of a queue, which means that only push to back, peek/pop from front, size and is empty operations are valid.

Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue's standard operations.

class MyStack {

    private Queue<Integer> data;//输入队列

    private Queue<Integer> helper;//输出队列


    public MyStack() {

        data = new LinkedList<>();

        helper = new LinkedList<>();

    }


    public void push(int x) {

        helper.offer(x);

        // 将b队列中元素全部转给a队列

        while(!data.isEmpty())

            helper.offer(data.poll());

        // 交换a和b,使得a队列没有在push()的时候始终为空队列

        Queue temp = helper;

        helper = data;

        data = temp;

    }


    public int pop() {

        return data.poll();

    }


    public int top() {

        return data.peek();

    }


    public boolean empty() {

        return data.isEmpty();

    }

}

/**

* Your MyStack object will be instantiated and called as such:

* MyStack obj = new MyStack();

* obj.push(x);

* int param_2 = obj.pop();

* int param_3 = obj.top();

* boolean param_4 = obj.empty();

*/

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容