225. 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 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).

用队列实现栈的功能

C++(2ms):

 1 class MyStack {
 2 public:
 3     queue<int> q ;
 4     /** Initialize your data structure here. */
 5     MyStack() {
 6         
 7     }
 8     
 9     /** Push element x onto stack. */
10     void push(int x) {
11         q.push(x) ;
12         for(int i = 0 ; i < q.size()-1 ; i++){
13             q.push(q.front()) ;
14             q.pop() ;
15         }
16     }
17     
18     /** Removes the element on top of the stack and returns that element. */
19     int pop() {
20         int t = q.front() ;
21         q.pop() ;
22         return t ;
23     }
24     
25     /** Get the top element. */
26     int top() {
27         return q.front() ;
28     }
29     
30     /** Returns whether the stack is empty. */
31     bool empty() {
32         return q.empty() ;
33     }
34 };
35 
36 /**
37  * Your MyStack object will be instantiated and called as such:
38  * MyStack obj = new MyStack();
39  * obj.push(x);
40  * int param_2 = obj.pop();
41  * int param_3 = obj.top();
42  * bool param_4 = obj.empty();
43  */
原文地址:https://www.cnblogs.com/mengchunchen/p/8295091.html