您的位置:首页 > 编程语言 > C语言/C++

单链队列,队列的链式存储结构C++实现

2014-05-28 12:25 344 查看
//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;
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++