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

用两个栈实现一个队列

时间:2016-05-01 20:32:25      阅读:280      评论:0      收藏:0      [点我收藏+]

标签:

用两个栈实现一个队列

 1 #include<iostream>
 2 #include<stdlib.h>
 3 #include<stack>
 4 using namespace std;
 5 
 6 template <typename T>class CQueue
 7 {
 8 public:
 9     CQueue(void);
10     ~CQueue(void);
11     void appendtail(const T& node);
12     T deleteHead();
13 private:
14     stack<T> stack1;
15     stack<T> stack2;
16 
17 };
18 
19 //构造函数
20 template <typename T> CQueue<T>::CQueue(void)
21 {
22 }
23 
24 //析构函数
25 template <typename T> CQueue<T>::~CQueue(void)
26 {
27 }
28 
29 //插入元素
30 template <typename T> void CQueue<T>::appendtail(const T& node)
31 {
32     stack1.push(node);
33 }
34 
35 //删除元素并返回
36 template <typename T> T CQueue<T>::deleteHead()
37 {
38     if(stack2.size()<=0)
39     {
40         while(stack1.size()>0)
41         {
42             stack2.push(stack1.top());
43             stack1.pop();
44         }
45     }
46     if(stack2.size()==0)
47         throw new exception("队列为空");
48     T head=stack2.top();
49     stack2.pop();
50     return head;
51 }
52 
53 void main()
54 {
55     CQueue<int> queue;
56     queue.appendtail(1);
57     queue.appendtail(2);
58     queue.appendtail(3);
59     queue.appendtail(4);
60     int len=4;
61     while(len>0)
62     {
63         cout<<queue.deleteHead()<<endl;
64         --len;
65     }
66     system("pause");
67 }

 

用两个栈实现一个队列

标签:

原文地址:http://www.cnblogs.com/wxdjss/p/5450969.html

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