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

.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中的一个值,即奇数和偶数配对输出,直到任一队列为空时止。


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值