首页 > 代码库 > 232. Implement Queue using Stacks
232. Implement Queue using Stacks
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.
- You must use only standard operations of a stack -- which means only
push to top
,peek/pop from top
,size
, andis 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。