栈————用队列实现栈

时间:2019-06-15
本文章向大家介绍栈————用队列实现栈,主要包括栈————用队列实现栈使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
 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  */

原文地址:https://www.cnblogs.com/pacino12134/p/11028628.html