码迷,mamicode.com
首页 > 其他好文 > 详细

232. Implement Queue using Stacks

时间:2017-07-14 23:53:01      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:anti   入栈   java   integer   机智   cal   push   str   native   

Implement the following operations of a queue using stacks.

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

第一想法是,push的时候直接把元素放入栈底,栈顶的元素保持为第一次入栈的元素,出栈时相当于出队。这种做法,push的时间复杂度是O(n),pop是O(1)。另外还需要一个stack,用来在push时存暂时出栈的元素。
机智的做法是!首先,如果一直在push,早已入栈的元素一直在两个栈之间push和pop,其次,stack把所有元素pop到另一个栈,实际上已经变成了一个queue
时间复杂度amortized o(1) 最差情况O(n)
什么是amortized o(1), 还有什么是amortized o(1)? 如ArrayList的add操作
public class MyQueue {
    Stack<Integer> stack;
    Stack<Integer> queue;
    /** Initialize your data structure here. */
    public MyQueue() {
        stack = new Stack<Integer>();
        queue = new Stack<Integer>();
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        stack.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        if (queue.empty()) {
            while (!stack.empty()) {
                queue.push(stack.pop());
            }
        }
        return queue.pop();
    }
    
    /** Get the front element. */
    public int peek() {
        if (queue.empty()) {
            while (!stack.empty()) {
                queue.push(stack.pop());
            }
        }
        return queue.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        if (stack.empty() && queue.empty()) {
            return true;
        } else {
            return false;
        }
    }
}

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * boolean param_4 = obj.empty();
 */

 

232. Implement Queue using Stacks

标签:anti   入栈   java   integer   机智   cal   push   str   native   

原文地址:http://www.cnblogs.com/yuchenkit/p/7173070.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!