一个功能简单的队列模板

这个代码写的时间比较短,也就是半个小时,测试的也不多,但是有一定的参考价值。

  1 #include <iostream>
  2 
  3 using namespace std;
  4 template<class T>
  5 class Queue
  6 {
  7 private:
  8 T *queuehead;
  9 int maxsize;
 10 int front;
 11 int rear;
 12 public:
 13 Queue(int max=10);
 14 ~Queue();
 15 bool Isempty();
 16 bool Isfull();
 17 bool addin(T & add);
 18 bool pop(T & out);
 19 void show();
 20 };
 21 template<class T>
 22 Queue<T>::Queue(int max)
 23 {
 24 if(max>0)
 25 maxsize=max;
 26 else
 27 maxsize=10;
 28 queuehead=new T [max];
 29 if(queuehead==NULL)
 30 abort();
 31 front=0;
 32 rear=0;
 33 }
 34 template<class T>
 35 Queue<T>::~Queue()
 36 {
 37 delete [] queuehead;
 38 }
 39 template<class T>
 40 bool Queue<T>::Isempty()
 41 {
 42 if(front==rear)
 43 return true;
 44 else
 45 return false;
 46 }
 47 template<class T>
 48 bool Queue<T>::Isfull()
 49 {
 50 if((rear+1)%maxsize==front)
 51 return true;
 52 else
 53 return false;
 54 }
 55 template<class T>
 56 bool Queue<T>::addin(T & add)
 57 {
 58 if(!Isfull())
 59 {
 60 queuehead[rear%=maxsize]=add;
 61 rear++;
 62 return true;
 63 }
 64 else
 65 return false;
 66 }
 67 template<class T>
 68 bool Queue<T>::pop(T & out)
 69 {
 70 if(!Isempty())
 71 {
 72 out=queuehead[front%=maxsize];
 73 front++;
 74 return true;
 75 }
 76 else
 77 return false;
 78 }
 79 template<class T>
 80 void Queue<T>::show()
 81 {
 82 cout<<"Data in line:\n";
 83 for(int i=0;i<maxsize;i++)
 84 cout<<queuehead[i]<<ends;
 85 cout<<endl;
 86 cout<<"rear:"<<rear<<endl;
 87 cout<<"front:"<<front<<endl;
 88 }
 89 int main()
 90 {
 91 cout << "Hello world!" << endl;
 92 int a;
 93 Queue<int> temp1;
 94 cin>>a;
 95 while(!cin.fail())
 96 {
 97 temp1.addin(a);
 98 cin>>a;
 99 }
100 while(!temp1.Isempty())
101 {
102 temp1.pop(a);
103 cout<<a<<ends;
104 }
105 cout<<endl;
106 temp1.show();
107 return 0;
108 }

转载于:https://www.cnblogs.com/matrix-r/archive/2012/11/10/2764493.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值