一个功能简单的队列模板
这个代码写的时间比较短,也就是半个小时,测试的也不多,但是有一定的参考价值。
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 }