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
, 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).
用栈来实现队列的功能
C++(3ms): 两个栈
1 class MyQueue { 2 public: 3 stack<int> st1 ; 4 stack<int> st2 ; 5 /** Initialize your data structure here. */ 6 MyQueue() { 7 8 } 9 10 /** Push element x to the back of queue. */ 11 void push(int x) { 12 st1.push(x) ; 13 } 14 15 /** Removes the element from in front of queue and returns that element. */ 16 int pop() { 17 move(); 18 int head = st2.top() ; 19 st2.pop() ; 20 return head ; 21 } 22 23 /** Get the front element. */ 24 int peek() { 25 move(); 26 return st2.top() ; 27 } 28 29 /** Returns whether the queue is empty. */ 30 bool empty() { 31 return st1.empty() && st2.empty() ; 32 } 33 34 void move(){ 35 if (st2.size() <= 0){ 36 while(st1.size() > 0){ 37 int t = st1.top() ; 38 st1.pop() ; 39 st2.push(t) ; 40 } 41 } 42 } 43 }; 44 45 /** 46 * Your MyQueue object will be instantiated and called as such: 47 * MyQueue obj = new MyQueue(); 48 * obj.push(x); 49 * int param_2 = obj.pop(); 50 * int param_3 = obj.peek(); 51 * bool param_4 = obj.empty(); 52 */
C++(0ms): 一个栈
1 class MyQueue { 2 public: 3 stack<int> st; 4 /** Initialize your data structure here. */ 5 MyQueue() { 6 7 } 8 9 /** Push element x to the back of queue. */ 10 void push(int x) { 11 pushHelper(x) ; 12 } 13 14 void pushHelper(int x){ 15 if (st.size() == 0){ 16 st.push(x) ; 17 return ; 18 } 19 int t = st.top() ; 20 st.pop() ; 21 pushHelper(x) ; 22 st.push(t) ; 23 return ; 24 } 25 26 /** Removes the element from in front of queue and returns that element. */ 27 int pop() { 28 int t = st.top() ; 29 st.pop() ; 30 return t ; 31 } 32 33 /** Get the front element. */ 34 int peek() { 35 return st.top() ; 36 } 37 38 /** Returns whether the queue is empty. */ 39 bool empty() { 40 return st.empty() ; 41 } 42 }; 43 44 /** 45 * Your MyQueue object will be instantiated and called as such: 46 * MyQueue obj = new MyQueue(); 47 * obj.push(x); 48 * int param_2 = obj.pop(); 49 * int param_3 = obj.peek(); 50 * bool param_4 = obj.empty(); 51 */
来源:https://www.cnblogs.com/mengchunchen/p/8241279.html