队列是一种先进先出的线性表。最典型的例子就是操作系统中的作业排队。每当通道传输完毕可以接受新的输出任务时,队头的作业先从队列中退出作输出操作。
下面是队列的C语言实现:
#include "stdio.h"
#include "stdafx.h"
#include "stdlib.h"
#define OK 1
#define ERROR 0
#define OVERFLOW 0
typedef struct QElemType{
int number;
};
typedef struct QNode{
QElemType data;
struct QNode *next;
} QNode, *QueuePtr;
typedef struct{
QueuePtr front;
QueuePtr rear;
}LinkQueue;
typedef int Status;
Status InitQueue(LinkQueue &Q);
Status DestroyQueue(LinkQueue &Q);
Status EnQueue(LinkQueue &Q, QElemType e);
Status DeQueue(LinkQueue &Q, QElemType &e);
Status InitQueue(LinkQueue &Q){
Q.front = Q.rear = (QueuePtr)malloc(sizeof(QNode));
if (!Q.front)exit(OVERFLOW);
Q.front->next = NULL;
return OK;
}
Status DestroyQueue(LinkQueue &Q){
while (Q.front)
{
Q.rear = Q.front->next;
free(Q.front);
Q.front = Q.rear;
}
return OK;
}
Status 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;
}
Status DeQueue(LinkQueue &Q, QElemType &e){
if (Q.front == Q.rear)return ERROR;
QueuePtr p;
p = Q.front->next;
e = p->data;
Q.front->next = p->next;
if (Q.rear == p) Q.rear = Q.front;
free(p);
return OK;
}