LeetCode.225 Implement Stack using Queues

来源:互联网 发布:巴丁算法集app 编辑:程序博客网 时间:2024/06/01 10:15

题目:

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).
分析:

class MyStack {    /** Initialize your data structure here. */    Queue<Integer> qu;    public MyStack() {        qu=new LinkedList<Integer>();    }        /** Push element x onto stack. */    public void push(int x) {        qu.add(x);    }        /** Removes the element on top of the stack and returns that element. */    public int pop() {        //出栈,由于队列只能从头取,所以需要把前n-1个元素放在队列后面,这样第n个元素才能出来        int size = qu.size();        for(int i = 1; i < size; i++)            qu.add(qu.remove());        return qu.remove();    }        /** Get the top element. */    public int top() {        //同理,取完之后,记得放回        int size = qu.size();        for(int i = 1; i < size; i++)            qu.add(qu.remove());        int res = qu.remove();        qu.add(res);        return res;    }        /** Returns whether the stack is empty. */    public boolean empty() {        return qu.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(); */


原创粉丝点击