使用链表来实现队列有其得天独厚的条件,链表灵活的节点删除和增加操作,对于实现队列来说尤其是小菜一碟。使用顺序表来实现队列还得为了有效使用空间而进行循环操作;即就是这样依然还会发生溢出现象,所以,还是链表来的爽快!
啥也不说,上代码
///////////////////////////////////////
//////////// LinkQueue.h
#include "stdafx.h"
#include
#include
#include
using namespace std; const int ERROR=-1; const int OK=1; typedef int Status; //表示操作结果的状态 ///非循环链队数据结构的C++说明 template
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
LinkQueue
::LinkQueue() { } template
LinkQueue
::~LinkQueue() { } template
void LinkQueue
::randLinkQueue() { srand(unsigned(time(NULL))); int n; ElemType Elem[11]; NodePointer p,s; n=rand()%10+1; cout<<"产生的随机数组为:"<
data=Elem[i]; s->next=NULL; if (front==NULL) front=rear=s; else { rear->next=s; rear=rear->next; } } display(); } template
void LinkQueue
::display() { NodePointer p; int n=0; p=front; cout<
data; p=p->next; n++; } cout<
Status LinkQueue
::deQueue(ElemType &e) { NodePointer p; p=front; if (p==NULL) return ERROR; e=p->data; front=p->next; delete p; return OK; } template
Status LinkQueue
::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
using namespace std; int _tmain(int argc, _TCHAR* argv[]) { LinkQueue
LQ; int a; LQ.randLinkQueue(); LQ.deQueue(a); LQ.display(); cout<<"输入要进入队列的元素:"<
>a; LQ.enQueue(a); LQ.display(); system("pause"); return 0; }