码迷,mamicode.com
首页 > 其他好文 > 详细

栈————用栈实现队列

时间:2019-06-15 20:05:39      阅读:83      评论:0      收藏:0      [点我收藏+]

标签:pop   structure   color   void   queue   returns   turn   call   nbsp   

技术图片

 1 class MyQueue {
 2 public:
 3     /** Initialize your data structure here. */
 4     MyQueue() {
 5         
 6     }
 7     stack<int> a;
 8     stack<int> b;
 9     /** Push element x to the back of queue. */
10     void push(int x) {
11         a.push(x);
12     }
13     
14     /** Removes the element from in front of queue and returns that element. */
15     int pop() {
16         int len=a.size();
17         for(int i=0;i<len;i++){
18             b.push(a.top());
19             a.pop();
20         }
21         int tmp=b.top();
22         b.pop();
23         for(int i=0;i<len-1;i++){
24             a.push(b.top());
25             b.pop();
26         }
27         return tmp;
28     }
29     
30     /** Get the front element. */
31     int peek() {
32         int len=a.size();
33         for(int i=0;i<len;i++){
34             b.push(a.top());
35             a.pop();
36         }
37         int tmp=b.top();
38         for(int i=0;i<len;i++){
39             a.push(b.top());
40             b.pop();
41         }
42         return tmp;
43     }
44     
45     /** Returns whether the queue is empty. */
46     bool empty() {
47         return a.empty();
48     }
49 };
50 
51 /**
52  * Your MyQueue object will be instantiated and called as such:
53  * MyQueue* obj = new MyQueue();
54  * obj->push(x);
55  * int param_2 = obj->pop();
56  * int param_3 = obj->peek();
57  * bool param_4 = obj->empty();
58  */

 

栈————用栈实现队列

标签:pop   structure   color   void   queue   returns   turn   call   nbsp   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!