LeetCode 225 Implement Stack using Queues

来源:互联网 发布:windows怎么更新系统 编辑:程序博客网 时间:2024/06/05 01:14

题目:

Implement the following operations of a stack using queues.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • empty() -- Return whether the stack is empty.
Notes:
  • You must use only standard operations of a queue -- which means only push to backpeek/pop from frontsize, and is empty operations are valid.
  • Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
  • You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
题目链接

题意:

要求实现一个基本栈的操作:push(int),pop(),top(),empty(),只能使用标准Queue中的操作。

在java中,Queue是一个接口,LinkedList类实现了这个接口,我们可以使用两个LinkedList来模拟Stack的操作,因为queue是先进先出,所以每次pop和top查询时利用两个queue,一个queue;不断pop,只到最后一项,然后返回最后一项,并将其他的项存入另一个queue中,来模拟stack的后进先出。

代码如下:

class MyStack {    private Queue<Integer> queue, temp;    public MyStack() {        queue = new LinkedList<>();        temp = new LinkedList<>();    }    public void push(int x) {        queue.offer(x);    }    public int pop() {        temp.clear();        while (queue.size() > 1) {            temp.offer(queue.poll());        }        int x = queue.poll();        queue = new LinkedList<>(temp);        return x;    }    public int top() {        temp = new LinkedList<>(queue);        while (temp.size() > 1) {            temp.poll();        }        return temp.poll();    }    public boolean empty() {        return queue.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(); */


原创粉丝点击