栈————用队列实现栈

 1 class MyStack {
 2 public:
 3     queue<int> q;
 4     /** Initialize your data structure here. */
 5     MyStack() {
 6         
 7     }
 8     /*
 9     --------------
10     push        pop
11                 front
12     */
13     /** Push element x onto stack. */
14     void push(int x) {
15         //push之后把x放到最前面就可以了
16         q.push(x);
17         for(int i=0;i<q.size()-1;i++){
18             q.push(q.front());
19             q.pop();
20         }
21     }
22     
23     /** Removes the element on top of the stack and returns that element. */
24     int pop() {
25         int tmp = q.front();
26         q.pop();
27         return tmp;
28     }
29     
30     /** Get the top element. */
31     int top() {
32         return q.front();
33     }
34     
35     /** Returns whether the stack is empty. */
36     bool empty() {
37         return q.empty();
38     }
39 };
40 
41 /**
42  * Your MyStack object will be instantiated and called as such:
43  * MyStack* obj = new MyStack();
44  * obj->push(x);
45  * int param_2 = obj->pop();
46  * int param_3 = obj->top();
47  * bool param_4 = obj->empty();
48  */

 

posted @ 2019-06-15 19:42  Austin_anheqiao  阅读(255)  评论(0编辑  收藏  举报