225. Implement Stack using Queues

来源:互联网 发布:机械三维设计软件排名 编辑:程序博客网 时间:2024/06/01 09:11

225. Implement Stack using Queues

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 back, peek/pop from front, size, 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).

解析:用队列实现栈,之前做过用两个栈实现队列,所以想到用两个栈来实现队列,但是看Discuss的时候看到 只用一个队列就可以。具体是:在新元素入队后,把这个元素之前的所有的元素都出队并且重新入队。这样就能保证最后插入队列的元素始终在队列的最前端,比如插入a,b,c,d这四个元素,队列中元素的顺序依次为a,ab,abc,abcd,这样插入的时间复杂度是O(n),弹出和获取最后一个元素的时间复杂度是O(1),是不是很奇妙?图示如下:


这里写图片描述

public class MyStack {    private Queue<Integer> queue;        /** Initialize your data structure here. */    public MyStack() {        queue = new LinkedList<>();            }        /** Push element x onto stack. */    public void push(int x) {        queue.offer(x);        for(int i = 0 ; i <queue.size()-1;i++){            queue.offer(queue.peek());            queue.poll();        }    }        /** Removes the element on top of the stack and returns that element. */    public int pop() {        return queue.poll();    }        /** Get the top element. */    public int top() {                return queue.peek();    }        /** Returns whether the stack is empty. */    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(); */



原创粉丝点击