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

Implement Queue using Stacks

时间:2015-07-07 22:35:44      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

主要思想:

申请两个辅助栈,一个用于进in,一个用于出out,倒腾一之后,在出之前变为FIFO即是队列

 1 class Queue {
 2     stack<int> in,out;
 3 public:
 4     // Push element x to the back of queue.
 5     void push(int x) {
 6         in.push(x);
 7     }
 8 
 9     // Removes the element from in front of queue.
10     void pop(void) {
11         checkOut();
12         out.pop();
13     }
14 
15     // Get the front element.
16     int peek(void) {
17         checkOut();
18         return out.top();
19         
20     }
21 
22     // Return whether the queue is empty.
23     bool empty(void) {
24         if(in.empty()&&out.empty())
25             return true;
26         return false;
27     }
28     void checkOut()
29     {
30         if(out.empty())
31         {
32             while(!in.empty())
33             {
34                 out.push(in.top());
35                 in.pop();
36             }
37         }
38     }
39 };

 

Implement Queue using Stacks

标签:

原文地址:http://www.cnblogs.com/aguai1992/p/4628619.html

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