队列的链式表示与实现

#include <iostream>
using namespace std;

#define QElemType int
#define ERROR 0
#define OK 1
#define FALSE 0
#define TRUE 1

//单链队列,队列的链式存储结构
typedef struct QNode
{
	QElemType data;
	struct QNode *next;
}QNode, *Queueptr;

typedef struct {
	Queueptr front;		//队头指针
	Queueptr rear;		//队尾指针
}LinkQueue;

//构造一个空队列Q
int InitQueue(LinkQueue &Q)
{
	Q.front = Q.rear = (Queueptr)malloc(sizeof(QNode));
	if(!Q.front)
		exit(OVERFLOW);
	Q.front->next = NULL;
	return OK;
}

//插入元素e为Q的新的队尾元素
int EnQueue(LinkQueue &Q,QElemType e )
{
	Queueptr p;
	p = (Queueptr)malloc(sizeof(QNode));
	if(!p)
		exit(OVERFLOW);
	p->data = e;
	p->next = NULL;
	Q.rear->next = p;
	Q.rear = p;
	return OK;
}

//输出队列元素
void QueueTraverse(LinkQueue Q)
{

	if(Q.front == Q.rear)
		cout << "队列空"<<endl;
	while(Q.front != Q.rear)
	{
		cout <<Q.front->next->data << " ";
		Q.front= Q.front->next;
	}
	cout << endl;
	
}
//若队列不空,则删除Q的队头元素,用e返回其值
void DeQueue(LinkQueue &Q,QElemType &e)
{
	if(Q.front == Q.rear)
		cout << "队列为空!" <<endl;
	Queueptr p;
	p = Q.front->next;
	e = p->data;
	Q.front->next = p->next;
	if(Q.rear == p)
		Q.rear = Q.front;
	free(p);
}

//销毁队列Q,Q不在存在
void DestoryQueue(LinkQueue &Q)
{
	while(Q.front != Q.rear)
	{
		Q.front= Q.front->next;
		free(Q.front);	
	}
}


//若队列Q清为队列
void ClearQueue(LinkQueue &Q)
{
	while(Q.front != Q.rear)
	{
		Q.front = Q.front->next;
		Q.front ->data = NULL;
	}

}

//若队列Q为空队列,则返回TRUE,否则返回FALSE
int QueueEmpty(const LinkQueue &Q)
{
	if(Q.front != Q.rear)
		return FALSE;
	else
		return TRUE;
}

//返回队列的长度
int QueueLength( LinkQueue Q)
{	
	int i = 0;
	while(Q.front != Q.rear)
	{
		++i;
		Q.front = Q.front->next;
	}
	return i;
}


//若队列不空,则用e返回Q的队头元素
int GetHead(LinkQueue Q,QElemType &e)
{
	if(QueueEmpty(Q))
		return ERROR;
	else
		e = Q.front->next->data;
	return e;
}

void main()
{
	LinkQueue Q;
	InitQueue(Q);
	QElemType e = 10;
	EnQueue(Q,e);
	QElemType m = 11;
	EnQueue(Q,m);
	QElemType o = 12;
	EnQueue(Q,o);
	QueueTraverse(Q);
//	QElemType n;
//	DeQueue(Q,n);
//	cout << n << endl;
//	DestoryQueue(Q);
//	ClearQueue(Q);
//	QueueTraverse(Q);
	cout << QueueLength(Q)<< endl;
	QElemType p ;
	GetHead(Q,p);
	cout << p << endl;

	system("pause");



}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值