代码的具体实现请参考第二个文章的单链表存储结构和第八章的循环队列存储结构,实现思想近似
#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR 0
typedef int Status;
typedef int ElemType;
typedef struct QueueNode
{
ElemType data;
struct QueueNode *next;
}QueueNode;
typedef QueueNode *QueueLink;
typedef struct
{
QueueLink front;
QueueLink rear;
int length;
}Queue;
//初始化
Status Init(Queue *q)
{
QueueLink qNode = (QueueLink)malloc(sizeof(QueueNode));
if(!qNode)
{
//exit(0);
return ERROR;
}
qNode -> next = NULL;
q -> front = qNode;
q -> rear = qNode;
q -> length = 0;
return OK;
}
//入队列
Status InQueue(Queue *q, ElemType elem)
{
QueueLink qNode = (QueueLink)malloc(sizeof(QueueNode));
if(!qNode) return ERROR;
q -> rear -> data = elem;
q -> rear -> next = qNode;
q -> rear = qNode;
q -> length ++;
return OK;
}
//出队列
Status OutQueue(Queue *q, ElemType *elem)
{
if(q -> length == 0) return ERROR;
QueueLink qNode;
qNode = q -> front;
q -> front = qNode -> next;
*elem = qNode -> data;
free(qNode);
q -> length --;
return OK;
}
//清空队列
Status Clear(Queue *q)
{
QueueLink qNode;
while(q -> length != 0)
{
qNode = q -> front;
q -> front = qNode -> next;
q -> length --;
free(qNode);
}
return OK;
}
int main(void)
{
Queue q;
Status statu;
statu = Init(&q);
if(statu == OK)
{
printf("%s : %d, %d, %d\n", "Init", q.front -> data, q.rear -> data, q.length);
statu = InQueue(&q, 21);
if(statu == OK)
{
printf("%s : %d, %d, %d\n", "InQueue", q.front -> data, q.rear -> data, q.length);
ElemType outElem;
statu = OutQueue(&q, &outElem);
if(statu == OK)
{
printf("%s : %d, %d, %d, %d\n", "OutQueue", q.front -> data, q.rear -> data, q.length, outElem);
// InQueue(&q, 22);
// InQueue(&q, 23);
// printf("%s : %d, %d, %d\n", "InQueue", q.front -> data, q.rear -> data, q.length);
statu = Clear(&q);
if(statu == OK)
{
printf("%s : %d, %d, %d\n", "Init", q.front -> data, q.rear -> data, q.length);
}
}
}
}
return 0;
}