Implement Stack using Queues

 1 class Stack {
 2     queue<int> input,output;
 3 
 4 public:
 5     // Push element x onto stack.
 6     void push(int x) {
 7         input.push(x);
 8         
 9     }
10 
11     // Removes the element on top of the stack.
12     void pop() {
13         
14         if(!input.empty()) 
15         {
16             int n=input.size();   //一开始没有设n,直接用size(),不行!!因为每删一次,size也在变
17             for(int i=0;i<n-1;i++)
18             {
19                 output.push(input.front());
20                 input.pop();
21                 
22             }
23             input.pop();
24             n=output.size();
25             for(int i=0;i<n;i++)
26             {
27                 input.push(output.front());
28                 output.pop();
29             }
30         }
31         output.push(input.back());
32            output.pop();
33         
34     }
35 
36     // Get the top element.
37     int top() {
38         if(!input.empty()) return input.back();
39         //else return -1;
40     }
41 
42     // Return whether the stack is empty.
43     bool empty() {
44         return input.empty();
45         
46     }
47 };

大神的代码

 1 class Stack {
 2 public:
 3     queue<int> que;
 4     // Push element x onto stack.
 5     void push(int x) {
 6         que.push(x);
 7         for(int i=0;i<que.size()-1;++i){
 8             que.push(que.front());
 9             que.pop();
10         }
11     }
12 
13     // Removes the element on top of the stack.
14     void pop() {
15         que.pop();
16     }
17 
18     // Get the top element.
19     int top() {
20         return que.front();
21     }
22 
23     // Return whether the stack is empty.
24     bool empty() {
25         return que.empty();
26     }
27 };
原文地址:https://www.cnblogs.com/daocaorenblog/p/4907550.html