队列(Queue)也是一种运算受限的线性表。它只允许在表的一端进行插入,而在另一端进行删除。允许删除的一端称为队头(front),允许插入的一端称为队尾(rear)。
1队列初始化
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define OK 1
#define ERROR 1
#define TRUE 1
#define FALSE 1
#define OVERFLOW -1
typedef int Status;
typedef int QElemType;
typedef struct QNode{/*定义结点*/
QElemType data;
struct QNode *next;
}QNode,*PtrQueue;
typedef struct{
PtrQueue front;/*队头队尾指针*/
PtrQueue rear;
}LinkQueue;
/*队列初始化*/
Status InitQueue(LinkQueue *Q)
{
Q->front=Q->rear=(PtrQueue)malloc(sizeof(QNode));//申请内存空间
if(!Q->front)
exit(OVERFLOW);
else
Q->front->next=NULL;/*构造一个空队列*/
return OK;
}
2销毁队列
/*销毁队列*/
Status DestroyQueue(LinkQueue *Q)
{
while(Q->front)
{
Q->rear=Q->front->next;
free(Q->front);
Q->front=Q->rear;
}
return OK;
}
3将队列清空
/*将队列清空*/
Status ClearQueue(LinkQueue *Q)
{
PtrQueue p,q;
Q->rear=Q->front;
p=Q->front->next;
while(p)
{
q=p;
p=p->next;
free(q);
}
return OK;
}
4判断队列是否为空
/*判断队列是否为空*/
Status EmptyQueue(LinkQueue Q)
{
if (Q.front==Q.rear)
{
return TRUE;
}
else
return FALSE;
}
5求队列的长度
/*求队列的长度*/
int QueueLength(LinkQueue Q)
{
int i=0;
PtrQueue p;
p=Q.front;
while(p!=Q.rear)
{
i++;
p=p->next;
}
return i;
}
6入队
/*入队*/
Status EnQueue(LinkQueue *Q,QElemType e)
{
PtrQueue s=(PtrQueue)malloc(sizeof(QNode));//新结点
if (!s)
exit(OVERFLOW);
s->data=e;
s->next=NULL;
Q->rear->next=s;
Q->rear=s;
return OK;
}
7出队
/*出队*/
Status DeQueue(LinkQueue *Q, QElemType *e)
{
PtrQueue p;
if (Q->front==Q->rear)
exit(OVERFLOW);
p=Q->front->next;//欲删除的队头结点
*e=p->data;
Q->front->next=p->next;
if (p==Q->rear)//若队头就是队尾,删除后队尾指向头结点
{
Q->rear=Q->front;
}
free(p);
return OK;
}
8遍历队列
/*遍历队列*/
Status TraverseQueue(LinkQueue Q)
{
PtrQueue p;
p=Q.front->next;
while(p)
{
printf("%d ",p->data);
p=p->next;
}
printf("\n");
return OK;
}
9主程序
int main()
{
int i;
int L;
QElemType e;//保存出队数据
LinkQueue Q;//定义一个队列
InitQueue(&Q);
printf("初始化后的长度为%d \n",QueueLength(Q));
for (i=1; i<10; i++)
{
EnQueue(&Q,i);
}
printf("入队1~9\n");
TraverseQueue(Q);
printf("队列长度:%d\n",L=QueueLength(Q));
printf("依次出队\n");
while (L)
{
DeQueue(&Q,&e);
printf("%d ",e);
L--;
}
printf("\n");
}
10程序运行结果