Common.h
#ifndef COMMON_H_INCLUDED
#define COMMON_H_INCLUDED
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int Status;
typedef int ElemType;
#endif // COMMON_H_INCLUDED
Queue_Linked.h
#ifndef QUEUE_LINKED_H_INCLUDED
#define QUEUE_LINKED_H_INCLUDED
#include "Common.h"
typedef struct QNode {
ElemType data;
struct QNode * next;
} QNode, * QueuePtr;
typedef struct {
QueuePtr front;//队头指针
QueuePtr rear;//队尾指针
} LinkQueue;
Status InitQueue(LinkQueue * q);
Status DestroyQueue(LinkQueue * q);
Status ClearQueue(LinkQueue * q);
Status QueueEmpty(LinkQueue * q);
int QueueLength(LinkQueue * q);
Status GetHead(LinkQueue * q, ElemType * e);
Status EnQueue(LinkQueue * q, ElemType e);
Status DeQueue(LinkQueue * q, ElemType * e);
Status QueueTraverse(LinkQueue * q);
#endif // QUEUE_LINKED_H_INCLUDED
Queue_Linked.c
#include "Queue_Linked.h"
Status InitQueue(LinkQueue * q)
{
q->front = (QNode *)malloc(sizeof(QNode));
q->rear = (QNode *)malloc(sizeof(QNode));
if(!q->front || !q->rear)
exit(OVERFLOW);
q->front->next = NULL;
q->rear = q->front;
return OK;
}
Status DestroyQueue(LinkQueue * q)
{
ClearQueue(q);
free(q);
return OK;
}
Status ClearQueue(LinkQueue * q)
{
ElemType * e = (ElemType *)malloc(sizeof(ElemType));
if(!e)
exit(OVERFLOW);
while(q->front != q->rear)
{
DeQueue(q, e);
}
return OK;
}
Status QueueEmpty(LinkQueue * q)
{
if(q->front == q->rear)
return TRUE;
else
return FALSE;
}
int QueueLength(LinkQueue * q)
{
int i = 0;
QNode * temp = q->front;
while(temp->next)
{
temp = temp->next;
i++;
}
return i;
}
Status GetHead(LinkQueue * q, ElemType * e)
{
if(!QueueEmpty(q))
{
*e = q->front->next->data;
return OK;
}
else
{
return ERROR;
}
}
Status EnQueue(LinkQueue * q, ElemType e)
{
QNode * temp = (QNode *)malloc(sizeof(QNode));
temp->data = e;
q->rear->next = temp;
q->rear = temp;
q->rear->next = NULL;
return OK;
}
Status DeQueue(LinkQueue * q, ElemType * e)
{
if(!QueueEmpty(q))
{
if(q->front->next == q->rear)
{
QNode * temp = q->front->next;
*e = temp->data;
q->rear = q->front;
q->rear->next = NULL;
free(temp);
}
else
{
QNode * temp = q->front->next;
*e = temp->data;
q->front->next = q->front->next->next;
free(temp);
}
return OK;
}
else
{
return ERROR;
}
}
Status QueueTraverse(LinkQueue * q)
{
QNode * temp = q->front->next;
while(temp)
{
printf("%d ", temp->data);
temp = temp->next;
}
return OK;
}