225. 用队列实现栈

 1 class MyStack 
 2 {
 3     queue<int> q1;//数据队列
 4     queue<int> q2;//临时队列
 5 public:
 6     MyStack() {}
 7     
 8     void push(int x) 
 9     {
10         q1.push(x);
11     }
12 
13     int pop() 
14     {
15         while(q1.size() > 1)
16         {
17             q2.push(q1.front());
18             q1.pop();
19         }
20         int temp = q1.front();
21         q1.pop();
22         swap(q1,q2);
23         return temp;
24     }
25 
26     int top() 
27     {
28         while(q1.size() > 1)
29         {
30             q2.push(q1.front());
31             q1.pop();
32         }
33         int temp = q1.front();
34         q2.push(q1.front());
35         q1.pop();
36         swap(q1,q2);
37         return temp;
38     }
39     
40     bool empty() 
41     {
42         return q1.empty();
43     }
44 };

 

posted @ 2020-04-11 22:36  Jinxiaobo0509  阅读(93)  评论(0)    收藏  举报