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

非循环链队类C++定义

2015-08-27 17:19 513 查看
使用链表来实现队列有其得天独厚的条件,链表灵活的节点删除和增加操作,对于实现队列来说尤其是小菜一碟。使用顺序表来实现队列还得为了有效使用空间而进行循环操作;即就是这样依然还会发生溢出现象,所以,还是链表来的爽快!

啥也不说,上代码

///////////////////////////////////////
////////////  LinkQueue.h

#include "stdafx.h"
#include <cassert>
#include<iomanip>
#include<iostream>
using namespace std;
const int ERROR=-1;
const int OK=1;
typedef int Status; //表示操作结果的状态

///非循环链队数据结构的C++说明
template<typename ElemType>
class LinkQueue
{
public:
class LinkNode
{
public:
ElemType data;
LinkNode * next;
};

typedef LinkNode*  NodePointer;

LinkQueue();
~LinkQueue();
void randLinkQueue();
void display();
void clear();
Status deQueue(ElemType &e);
Status enQueue(ElemType &e);

private:
NodePointer front;
NodePointer rear;

};

///////////////////////////////////////
//  自动调用构造函数和析构函数
template<typename ElemType>
LinkQueue<ElemType>::LinkQueue()
{
}
template <typename ElemType>
LinkQueue<ElemType>::~LinkQueue()
{
}

template<typename ElemType>
void LinkQueue<ElemType>::randLinkQueue()
{
srand(unsigned(time(NULL)));
int n;
ElemType Elem[11];
NodePointer p,s;
n=rand()%10+1;
cout<<"产生的随机数组为:"<<endl;
for (int i = 0; i < n; i++)
{
Elem[i]=rand()%100+1;
cout<<setw(6)<<Elem[i];
}

front=NULL;
for (int i = 0; i < n; i++)
{
s=new(LinkNode);
assert(s!=0);
s->data=Elem[i];
s->next=NULL;
if (front==NULL)
front=rear=s;
else
{
rear->next=s;
rear=rear->next;
}
}

display();

}

template<typename ElemType>
void LinkQueue<ElemType>::display()
{
NodePointer p;
int n=0;
p=front;
cout<<endl<<"产生的非循环链队为:"<<endl;
while (p!=NULL)
{
cout<<setw(6)<<p->data;
p=p->next;
n++;
}
cout<<endl;
cout<<setw(6)<<"↑";
for (int i = 0; i < n-2; i++)
{
cout<<setw(6)<<" ";
}
cout<<setw(6)<<"↑"<<endl;
cout<<endl;
cout<<setw(6)<<"front";
for (int i = 0; i < n-2; i++)
{
cout<<setw(6)<<" ";
}
cout<<setw(6)<<"rear"<<endl;
}

template<typename ElemType>
Status LinkQueue<ElemType>::deQueue(ElemType &e)
{
NodePointer p;
p=front;
if (p==NULL)
return ERROR;
e=p->data;
front=p->next;
delete p;
return OK;
}

template<typename ElemType>
Status LinkQueue<ElemType>::enQueue(ElemType &e)
{
NodePointer s;
s=new(LinkNode);
assert(s!=0);
s->data=e;
s->next=NULL;
if(front==NULL)
front=rear=s;
rear->next=s;
return OK;

}


// LinkQueueTest.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include"LinkQueue.h"
#include<iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
LinkQueue<int> LQ;
int a;
LQ.randLinkQueue();
LQ.deQueue(a);
LQ.display();
cout<<"输入要进入队列的元素:"<<endl;
cin>>a;
LQ.enQueue(a);
LQ.display();
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: