#include <iostream>
#include <cstdio>
#include <malloc.h>
using namespace std;
#define OVERFLOW 0
#define TRUE 1
#define FLASE 0
#define OK 1
#define ERROR 0
typedef int Status;
typedef int QElemType;
typedef struct QNode
{
QElemType data;
QNode *next;
}*QueueRtr;
struct LinkQueue
{
QueueRtr ifront,irear;
};
//初始准备
void InitQueue(LinkQueue &Q);
void DestroyQueue(LinkQueue &Q);
void ClearQueue(LinkQueue &Q);
Status QueueEmpty(LinkQueue Q);
int QueueLength(LinkQueue Q);
void EnQueue(LinkQueue &Q,QElemType e);//插入元素e为队列的新的队尾元素
Status DeQueue(LinkQueue &Q,QElemType &e);//若队列Q不空,删除Q的队头元素,用e返回其值
void QueueTraverse(LinkQueue &Q);
Status GetHead(LinkQueue Q,QElemType e); //得到队头元素
void InitQueue(LinkQueue &Q)
{
Q.ifront=Q.irear=(QueueRtr)malloc(sizeof(QNode));//生成头结点
if(!Q.ifront)
exit(OVERFLOW);
Q.ifront->next=NULL;//头结点的next域为空
}
void DestroyQueue(LinkQueue &Q)
{
while(Q.ifront) //Q.ifront不为空
{
Q.irear=Q.ifront->next;//Q.rear指向Q.front的下一个结点
free(Q.ifront);//释放Q.front所指的结点
Q.ifront=Q.irear; //Q.front指向Q,front的下一个结点
}
}
Status GetHead(LinkQueue Q,QElemType e)
{
QueueRtr p;
if(Q.ifront==Q.irear)
return ERROR; //队列空
p=Q.ifront->next;//p指向队头结点
e=p->data; //将队头元素的值赋给e
return e;
}
void ClearQueue(LinkQueue &Q)
{
DestroyQueue(Q); //销毁队列Q
InitQueue(Q); //重新构造空队列
}
Status QueueEmpty(LinkQueue Q)
{
if(Q.ifront->next==NULL)
return TRUE;
else
return FLASE;
}
int QueueLength(LinkQueue Q)
{
int i=0;
QueueRtr p=Q.ifront;//p指向头结点
while(Q.irear!=p) //p所指的不是尾结点
{
i++;
p=p->next; //p指向下一个结点
}
return i;
}
void EnQueue(LinkQueue &Q,QElemType e)
{//插入元素e为队列的新的队尾元素
QueueRtr p;
p=(QueueRtr)malloc(sizeof(QNode));
if(!p)
exit(OVERFLOW);
p->data=e; //将e赋值给新结点
p->next=NULL; //新结点的指针域为空
Q.irear->next=p; //原队尾结点的指针指向新结点
Q.irear=p; // 尾指针指向新结点
}
Status DeQueue(LinkQueue &Q,QElemType &e)
{//若队列Q不空,删除Q的队头元素,用e返回其值
QueueRtr p;
if(Q.ifront==Q.irear)
return ERROR;
p=Q.ifront->next;//p指向队头
e=p->data; //赋值
Q.ifront->next=p->next;//头节点指向下一个结点
if(Q.irear==p) //s删除的是队尾结点
Q.irear=Q.ifront;
free(p);
return OK;
}
void QueueTraverse(LinkQueue &Q)
{
QueueRtr p=Q.ifront->next;
while(p)
{
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}
int main()
{
QElemType d;
LinkQueue q;
InitQueue(q);
printf("成功构造了一个空队列\n");
printf("队列是否为空?(YES:1 NO:0)%d\n",QueueEmpty(q));
printf("队列的长度为:%d\n",QueueLength(q));
EnQueue(q,1);//入队3个元素
EnQueue(q,-1);
EnQueue(q,0);
printf("队列是否为空?(YES:1 NO:0)%d\n",QueueEmpty(q));
printf("插入元素后队列长度为:%d\n",QueueLength(q));
printf("队列元素依次为:");
QueueTraverse(q);
printf("队头元素:%d\n",GetHead(q,d));
DeQueue(q,d);
printf("删除了队头元素:%d\n",d);
int k,i=GetHead(q,k);
printf("新的队头元素为:%d\n",i);
ClearQueue(q);
printf("清空队列后q.ifront=%d,q.irear=%d q.ifront->next=%d\n",q.ifront,q.irear,q.ifront->next);
//DestroyQueue(q);
printf("队列是否为空?(YES:1 NO:0)%d\n",QueueEmpty(q));
//printf("销毁队列后q.ifront=%d,q.irear=%d q.ifront->next=%d\n",q.ifront,q.irear,q.ifront->next);
return 0;
}
队列模板
最新推荐文章于 2022-07-15 17:40:22 发布