#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define TRUE 1
#define ERROR 0
typedef int Status;
typedef int QElemType;
typedef struct QNode {
QElemType data;
struct QNode * next;
}QNode, *QueuePtr;
typedef struct {
QueuePtr front;
QueuePtr rear;
}LinkQueue;
//初始化队列
Status InitQueue_L(LinkQueue &Q)
{
Q.front = (QueuePtr) malloc (sizeof(QNode));
if (Q.front == NULL)
exit(OVERFLOW);
Q.front->next = NULL;
Q.rear = Q.front;
return OK;
}
//创建一个队列
void CreatQueue(LinkQueue &Q)
{
int n;
printf("请输入循环队列的长度:");
scanf("%d",&n);
for (int i = 1; i <=n; i++)
{
printf("第%d个元素为:",i);
scanf("%d",&Q.base[Q.rear]);
Q.rear=(Q.rear+1)%MAXQSIZE;
}
}
// 插入元素e为Q的新的队尾元素
Status EnQueue(SqQueue &Q,QElemType e)
{
if((Q.rear+1)%MAXQSIZE==Q.front)
return ERROR;
Q.base[Q.rear]=e;
Q.rear=(Q.rear+1)%MAXQSIZE;
return Q.base[Q.rear-1];
}
Status InsertQueue(LinkQueue &Q,QElemType e) //插入元素e为Q的队尾元素
{
QueuePtr p = (QueuePtr)malloc(sizeof(QNode));
if(!p)exit(OVERFLOW);
p->data = e; //赋值
p->next = NULL;
Q.rear->next = p; //连接
Q.rear = p; //新的队尾
return OK;
}
//删除队列
Status DeQueue(LinkQueue &Q ) //在队列不为空的情况下,删除队头元素
{
QElemType e;
if(Q.front==Q.rear)
return ERROR;
e=Q.base[Q.front];
Q.front=(Q.front+1)%MAXQSIZE;
return e;
}
//获取队头元素
Status GetFront(LinkQueue Q,QElemType &e)
{
if (Q.front == Q.rear)
{
return ERROR;
}
e = Q.front->next->data;
return e;
}
Status QueueEmpty(LinkQueue Q)
{
if(Q.front == Q.rear)
{
return TRUE;
}
else
{
return ERROR;
}
}
//输出队列
Status PrintQueue(LinkQueue Q)
{
QNode *p;
p = Q.front->next;
printf("the queue is:");
while(p != NULL)
{
printf("%d ", p->data);
p = p->next;
}
return OK;
}
//判断队列是否为空
Status EmptyQueue(LinkQueue Q)
{
if (Q.front->next == NULL)
return OK;
return ERROR;
}
//队列的销毁
void DstoryQueue(SqQueue &Q)
{
while ( Q.front!= Q.rear)
{
free(&Q.base[Q.front]);
Q.front=(Q.front+1)%MAXQSIZE;
}
}
//清空队列
void ClearQueue(SqQueue &Q)
{
int i=Q.front;
while (i != Q.rear)
{
i=0;
i++;
}
Q.front=Q.rear=0;
}
//求队列长度
Status QueueLength(SqQueue Q)
{
return (Q.rear-Q.front+MAXQSIZE)%MAXQSIZE;
}
//取队首元素
Status GetHead(SqQueue &Q)
{
QElemType e;
if(Q.front==Q.rear)
return ERROR;
return e=Q.base[Q.front];
}
ADT - 队列
最新推荐文章于 2022-07-11 17:21:01 发布