您的位置:首页 > 其它

使用队列的程序举例(2)

2018-04-03 20:49 344 查看
.h文件:
/*循环队列的链式存储*/

//初始化
void InitQueue(LinkQueue &HQ)
{
HQ.front = HQ.rear = NULL;
}

//清空队列
void ClearQueue(LinkQueue &HQ)
{
LNode *p = HQ.front;
while(p != NULL)
{
HQ.front = p->next;
delete p;
p = HQ.front->next;
}
HQ.front->next = NULL;
}

//检查队列是否为空
int QueueEmpty(LinkQueue &HQ)
{
return (HQ.front == NULL);
}

//读取队首元素
ElemType QFront(LinkQueue &HQ)
{
if(HQ.front == NULL)
{
cerr<<"Linked queue is empty!"<<endl;
exit(1);
}
return HQ.front->data;
}

//插入元素
void QInsert(LinkQueue &HQ,const ElemType &item)
{
LNode *newptr = new LNode;
if(newptr == NULL)
{
cerr<<"Memory allocation failare!"<<endl;
exit(1);
}
newptr->data = item;
newptr->next = NULL;
if(HQ.rear == NULL)
HQ.front = HQ.rear = newptr;
else
{
HQ.rear->next = newptr;
HQ.rear = newptr;
}
}

//删除元素
ElemType QDelete(LinkQueue &HQ)
{
ElemType temp = QFront(HQ);
LNode *p = HQ.front;    //暂存队首指针以便回收队首结点
HQ.front = p->next;
if(HQ.front == NULL)
HQ.rear = NULL;     //若队列变为空,则需同时使队尾指针变为空
delete p;   //回收原队首结点
return temp;
}

.cpp文件:#include <iostream>

using namespace std;

typedef int ElemType;

const int QueueMaxSize = 50;

struct LNode
{
ElemType data;
LNode *next;
};

struct LinkQueue
{
LNode *front;
LNode *rear;
};

#include "queue.h"

int main()
{
LinkQueue q1,q2;
InitQueue(q1);
InitQueue(q2);
for(int i = 0; i < 20; i++)
{
int x = rand() % 100;
cout<<x<<" ";
if(x % 2)
QInsert(q1,x);
else
QInsert(q2,x);
}
cout<<endl;
cout<<"q1 q2"<<endl;
while(!QueueEmpty(q1) && !QueueEmpty(q2))
cout<<QDelete(q1)<<" "<<QDelete(q2)<<endl;
return 0;
}
此程序使用了两个链队q1和够,用来分别存储由计算机随机产生的20个100以内的奇数和偶数,然后每行输出q1和q2中的一个值,即奇数和偶数配对输出,直到任一队列为空时止。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: