#include "stdio.h"
#include "stdlib.h"
#include "io.h"
#include "math.h"
#include "time.h"
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define MAXSIZE 20 /* 存储空间初始分配量 */
typedef int Status;
typedef int QElemType; /* QElemType类型根据实际情况而定,这里假设为int */
typedef struct QNode /* 结点结构 */
{
QElemType data;
struct QNode *next;
}QNode,*QueuePtr;
typedef struct /* 队列的链表结构 */
{
QueuePtr front,rear; /* 队头、队尾指针 */
}LinkQueue;
Status visit(QElemType c)
{
printf("%d ",c);
return OK;
}
/* 构造一个空队列Q */
Status InitQueue(LinkQueue *Q)
{
Q->rear = Q->front = (QueuePtr)malloc(sizeof(QNode));
if (Q->rear ==NULL)
{
exit(OVERFLOW); /*内存不足*/
}
Q->front->next = NULL;
return OK;
}
/* 销毁队列Q */
Status DestroyQueue(LinkQueue *Q)
{
/*QueuePtr p = NULL;
while (Q->front != Q->rear)
{
p = Q->front->next;
free(Q->front);
Q->front = p;
}
free(Q->rear);
Q->rear = Q->front = NULL;*/
while(Q->front)
{
Q->rear = Q->front->next;
free(Q->front);
Q->front = Q->rear;
}
}
/* 将Q清为空队列 链表类型的数据结构一定有头结点,指针删除结点必须2个只指针*/
Status ClearQueue(LinkQueue *Q)
{
QueuePtr p,q;
Q->rear = Q->front;
p = Q->front->next;
while (p)
{
q = p;
free(p);
p =q;
}
return OK;
}
/* 若Q为空队列,则返回TRUE,否则返回FALSE */
Status QueueEmpty(LinkQueue Q)
{
if(Q.front==Q.rear)
return TRUE;
else
return FALSE;
}
/* 求队列的长度 */
int QueueLength(LinkQueue Q)
{
QueuePtr p;
int i = 0;
p = Q.front;
while (p != Q.rear)
{
i++;
p = p->next;
}
return i;
}
/* 若队列不空,则用e返回Q的队头元素,并返回OK,否则返回ERROR */
Status GetHead(LinkQueue Q,QElemType *e)
{
if (Q.rear == Q.front)
{
return ERROR;
}
*e = Q.front->next->data;
return OK;
}
/* 插入元素e为Q的新的队尾元素 */
Status EnQueue(LinkQueue *Q,QElemType e)
{
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;
}
/* 若队列不空,删除Q的队头元素,用e返回其值,并返回OK,否则返回ERROR */
Status DeQueue(LinkQueue *Q,QElemType *e)
{
QueuePtr p;
if(Q->front==Q->rear)
return ERROR;
p=Q->front->next; /* 将欲删除的队头结点暂存给p,见图中① */
*e=p->data; /* 将欲删除的队头结点的值赋值给e */
Q->front->next=p->next;/* 将原队头结点的后继p->next赋值给头结点后继,见图中② */
if(Q->rear==p) /* 若队头就是队尾,则删除后将rear指向头结点,见图中③ */
Q->rear=Q->front;
free(p);
return OK;
}
Status TraverseQueue(LinkQueue q)
{
QueuePtr p;
p = q.front->next;
while(p)
{
visit(p->data);
p = p->next;
}
return OK;
}
void main()
{
LinkQueue q;
int i;
InitQueue(&q);
EnQueue(&q,1);
EnQueue(&q,2);
EnQueue(&q,3);
DeQueue(&q,&i);
TraverseQueue(q);
getchar();
}
队列的链式存储
最新推荐文章于 2024-05-26 19:24:51 发布