LeetCode 225. Implement Stack using Queues
原题链接在这里:https://leetcode.com/problems/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
, andis 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).
题解:
与Implement Queue using Stacks相对应。
用一个queue来实现stack. push时从queue尾add进去, 然后rotate了que.size()-1次.
pop()时从queue首 poll 出一个. top()是 peek() 一下.
Time Complexity: push, O(n). pop, O(1). peek, O(1). empty, O(1).
Space: O(n), queue size.
AC java:
1 public class MyStack { 2 3 Queue<Integer> que; 4 /** Initialize your data structure here. */ 5 public MyStack() { 6 que = new LinkedList<Integer>(); 7 } 8 9 /** Push element x onto stack. */ 10 public void push(int x) { 11 que.offer(x); 12 for(int i = 0; i<que.size()-1; i++){ 13 que.offer(que.poll()); 14 } 15 } 16 17 /** Removes the element on top of the stack and returns that element. */ 18 public int pop() { 19 return que.poll(); 20 } 21 22 /** Get the top element. */ 23 public int top() { 24 return que.peek(); 25 } 26 27 /** Returns whether the stack is empty. */ 28 public boolean empty() { 29 return que.isEmpty(); 30 } 31 } 32 33 /** 34 * Your MyStack object will be instantiated and called as such: 35 * MyStack obj = new MyStack(); 36 * obj.push(x); 37 * int param_2 = obj.pop(); 38 * int param_3 = obj.top(); 39 * boolean param_4 = obj.empty(); 40 */
AC C++:
1 class MyStack { 2 public: 3 queue<int> que; 4 MyStack() { 5 } 6 7 void push(int x) { 8 que.push(x); 9 for(int i = 0; i < que.size() - 1; i++){ 10 que.push(que.front()); 11 que.pop(); 12 } 13 } 14 15 int pop() { 16 int temp = que.front(); 17 que.pop(); 18 return temp; 19 } 20 21 int top() { 22 return que.front(); 23 } 24 25 bool empty() { 26 return que.empty(); 27 } 28 }; 29 30 /** 31 * Your MyStack object will be instantiated and called as such: 32 * MyStack* obj = new MyStack(); 33 * obj->push(x); 34 * int param_2 = obj->pop(); 35 * int param_3 = obj->top(); 36 * bool param_4 = obj->empty(); 37 */