シングルチェーンキュー、キューのチェーンストレージ構造C++実現

1991 ワード

//mList.cpp
/*
	            
	@author:    
	@date:2014-5-28
	@version:2.0
*/
#include <iostream>
using namespace std;
template<class T>
class Queue
{
private:
	static const int MAX=100 ;//       
	//    
	struct QNode{
	T data;//   
	QNode *next;
	};
	QNode *front;//     
	QNode *rear;//     
	int count;//    
public:
	//     
	Queue(){
		front=rear=nullptr;
		count=0;
	}
	~Queue(){
		QNode *temp=front;
		QNode *p=temp;
		cout<<endl;
		while(temp!=nullptr){
			temp=temp->next;
			cout<<"delete "<<p->data<<endl;
			delete p;
			p=temp;		
		}
	}
	//    
	bool EnQueue(T &t){
		QNode *p=new QNode;
		p->data=t;
		p->next=nullptr;
		if(nullptr==front){//        
			front=rear=p;
			count++;
			front->next=nullptr;
			return true;
		}else if(!isFull()){//        
		rear->next=p;
		rear=p;//       ,rear=p
		//rear->next=nullptr;//       ,rear=p->next=nullptr;
		count++;
		return true;
		}else
			return false;
			
	}
	//     
	bool DeleteQueue(){
		if(isEmpty()){//        
			cout<<"Queue is Empty!Can't delte it!"<<endl;
			return false;
		}
		QNode *temp=front;
		front=front->next;
		delete temp;
		count--;
		return true;

	}
	int Length()const{
		return count;
	}
	void show()const{
		QNode *temp=front;
		while(temp!=nullptr){
			cout<<temp->data<<" ";
			temp=temp->next;
		}
	}
protected:
	bool isEmpty()const{
		return count==0;
	}
	bool isFull()const{
		if(count==MAX){
			cout<<"Queue full!"<<endl;
			return true;
		}
		return false;
	}




};
<pre name="code" class="cpp">int main()
{
	{
	Queue<int> q;
	for(int i=1;i<103;i++)
		q.EnQueue(i);
	cout<<endl;
	q.show();
	cout<<endl;
	for(int j=0;j<102;j++)
	  q.DeleteQueue();
	}
	system("pause");
	return 0;
}