C++面向对象实现链式队列
结点类:
class LinkNode
{
public:
int data;
LinkNode *next;
};
队列类:
class LQueue
{
public:
LQueue();
virtual ~LQueue();
void InitQueue(LQueue &);
void EnQueue(LQueue &,int&);
void TraverseQueue(LQueue &);
bool isEmpty(LQueue &);
bool DelQueue(LQueue&,int&);
protected:
private:
LinkNode *front,*rear;
};
LQueue::LQueue()
{
}
LQueue::~LQueue()
{
}
void LQueue::InitQueue(LQueue &LQ)
{
LQ.front=LQ.rear= new LinkNode [sizeof(LinkNode)];
LQ.front->next=NULL;
}
void LQueue::EnQueue(LQueue &LQ,int& val)
{
LinkNode* q=LQ.rear;
LinkNode* p=(LinkNode*)malloc(sizeof(LinkNode));
p->data=val;
p->next=NULL;
q->next=p;
LQ.rear=p;
}
bool LQueue::isEmpty(LQueue &LQ)
{
if(LQ.front==LQ.rear)
return true;
else
return false;
}
void LQueue::TraverseQueue(LQueue &LQ)
{
LinkNode* p;
if(isEmpty(LQ))
{
cout<<"空队列!"<<endl;
return;
}
p=LQ.front->next;
while(p!=NULL)
{
cout<<"元素为"<<p->data<<endl;
p=p->next;
}
}
bool LQueue::DelQueue(LQueue& LQ,int&x)
{
if(isEmpty(LQ))
return false;
LinkNode *p=LQ.front->next;
x=p->data;
LQ.front->next=p->next;
if(LQ.rear==p)
LQ.rear=LQ.front;
free(p);
return true;
}
主函数
#include <iostream>
#include <malloc.h>
using namespace std;
int main()
{
int x[]={2,3,4,6};
int val=0;
LQueue Lq;
LQueue LQ2;
LQueue Q;
Lq.InitQueue(Q);
Lq.InitQueue(LQ2);
for(int i=0;i<(int)(sizeof(x)/sizeof(int));i++)
{
Lq.EnQueue(Q,x[i]);
}
cout<<"Q队伍为"<<endl;
Lq.TraverseQueue(Q);
Lq.DelQueue(Q,val);
cout<<"出队元素为\t"<<val<<endl;
cout<<"出队后"<<endl;
Lq.TraverseQueue(Q);
cout<<"LQ2队伍为";
Lq.TraverseQueue(LQ2);
return 0;
}