头文件
#ifndef _LINKQUEUE_H
#define _LINKQUEUE_H
#define SUCCESS 10000
#define FAILURE 10001
#define TRUE 10002
#define FALSE 10003
struct node
{
int data;
struct node *next;
};
typedef struct node Node;
struct queue
{
Node *front;
Node *rear;
};
typedef struct queue Q;
int QueueInit(Q **q);
int QueueInsert(Q *queue,int e);
int DeleteQueue(Q *q);
int GetFront(Q *q);
int QueueEmpty(Q *q);
int ClearQueue(Q *q);
int QueueDestroy(Q **q);
#endif
函数
#include "LInkQueue.h"
#include <stdio.h>
#include <stdlib.h>
int QueueInit(Q **q)
{
(*q) = (Q *)malloc(sizeof(Q));
if((*q) == NULL)
{
return FAILURE;
}
Node *p = (Node *)malloc(sizeof(Node));
if(p == NULL)
{
return FAILURE;
}
p->next = NULL;
(*q)->front = (*q)->rear = p;
return SUCCESS;
}
int QueueInsert(Q *queue,int e)
{
if(NULL == queue)
{
return FAILURE;
}
Node *q = (Node *)malloc(sizeof(Node));
if(NULL == q)
{
return FAILURE;
}
q->data = e;
q->next = NULL;
queue->rear->next = q;
queue->rear = q;
return SUCCESS;
}
int DeleteQueue(Q *q)
{
if(NULL == q || q->rear == q->front)
{
return FAILURE;
}
int e;
Node *p = q->front->next;
e = p->data;
q->front->next = p->next;
if(!p->next)
{
q->rear = q->front;
}
free(p);
return e;
}
int GetFront(Q *q)
{
if(NULL == q || q->front == q->rear)
{
return FAILURE;
}
return q->front->next->data;
}
int QueueEmpty(Q *q)
{
if(NULL == q)
{
return 1;
}
return(q->front == q->rear) ? TRUE : FALSE;
}
int ClearQueue(Q *q)
{
if(NULL == q)
{
return FAILURE;
}
Node *p = q->front->next;
while(p)
{
q->front->next = p->next;
free(p);
p = q->front->next;
}
q->rear=q->front;
return SUCCESS;
}
int QueueDestroy(Q **q)
{
if(NULL == q || NULL == (*q))
{
return FAILURE;
}
free((*q)->front);
free(*q);
*q = NULL; //为了使queue不为野指针
return SUCCESS;
}
主函数
#include "LinkQueue.h"
#include <stdio.h>
int main()
{
Q *queue;
int ret,i;
ret = QueueInit(&queue);
if(ret == SUCCESS)
{
printf("Init Success!\n");
}
else
{
printf("Init Failure!\n");
}
for(i = 0; i < 5; i++)
{
ret = QueueInsert(queue,i);
if(FAILURE == ret)
{
printf("Insert Failure!\n");
}
else
{
printf("Insert %d is Success!\n",i);
}
}
for(i = 0; i < 3; i++)
{
ret = DeleteQueue(queue);
if(ret == FAILURE)
{
printf("Delete Failure!\n");
}
else
{
printf("Delete %d Success!\n",i);
}
}
ret = GetFront(queue);
if(ret == FAILURE)
{
printf("Get Front Failure!\n");
}
else
{
printf("Front is %d\n",ret);
}
ret = QueueEmpty(queue);
if(ret == TRUE)
{
printf("Queue is Empty!\n");
}
else
{
printf("Queue is not Empty!\n");
}
ret = ClearQueue(queue);
if(ret == SUCCESS)
{
printf("Clear Success!\n");
}
else
{
printf("Clear Failure!\n");
}
ret = QueueDestroy(&queue);
if(ret == SUCCESS)
{
printf("Destroy Success!\n");
}
else
{
printf("Destroy Failure!\n");
}
return 0;
}
注意点:在需要修改变量的值时,需要取地址,比如初始化和销毁的时候,q指向queue这个结构体,这个结构体有两个指针,指针指向队列信息,初始化时涉及到队列内容,所以需要取值,Q **q;