定义
特点:先进先出(FIFO)
队尾:入队操作
队头:出队操作
.h文件
typedef int datatype;
typedef struct node
{
datatype data;
struct node *next;
}listnode, *linklist;
typedef struct _linkqueue {
linklist front;
linklist rear;
}linkqueue;
linkqueue* queue_create();
int enqueue(linkqueue *lq, datatype x);
datatype dequeue(linkqueue *lq);
int queue_empty(linkqueue *lq);
int queue_clear(linkqueue *lq);
linkqueue* queue_free(linkqueue *lq)
.c文件
#include <stdio.h>
#include <stdlib.h>
#include "linkqueue.h"
linkqueue* queue_create()
{
linkqueue *lq = (linkqueue *)malloc(sizeof(linkqueue));
if(lq == NULL){
printf("malloc linkqueue fail\n");
return NULL;
}
lq->front = lq->rear = (linklist)malloc(sizeof(listnode));
if(lq->front == NULL){
printf("malloc listnode fail\n");
return NULL;
}
lq->front->data = 0;
lq->front->next = NULL;
return lq;
}
int enqueue(linkqueue *lq, datatype x){
if(lq == NULL){
printf("lq is NULL\n");
return -1;
}
linklist p= (linklist)malloc(sizeof(listnode));
if(p == NULL){
printf("malloc node fail\n");
return -1;
}
p->data = x;
p->next = NULL;
lq->rear->next = p;//连接
lq->rear = p;//移位
return 0;
}
datatype dequeue(linkqueue *lq){
linklist p;
datatype temp;
if (lq == NULL){
printf("lq is NULL\n");
return 0;
}
if (lq->front == lq->rear){
printf("lq is empty\n");
return 0;
}
p = lq->front;
lq->front= p->next;
temp = lq->front->data;
free(p);
p = NULL;
return temp;
}
int queue_empty(linkqueue *lq){
if (lq == NULL){
printf("lq is NULL\n");
return -1;
}
if (lq->front == lq->rear){
printf("linkqueue is empty\n");
return -1;
}
return 0;
}
int queue_clear(linkqueue *lq){
linklist p;
if (lq == NULL){
printf("lq is NULL\n");
return 0;
}
while (!(lq->front == lq->rear))
{
p = lq->front;
lq->front = p->next;
printf("clear:%d\n",p->data);
free(p);
p = NULL;
}
return 0;
}
linkqueue* queue_free(linkqueue *lq){
linklist p;
if (lq == NULL){
printf("lq is NULL\n");
return 0;
}
p = lq->front;
while (lq->front)
{
lq->front = p->next;
printf("free:%d\n",p->data);
free(p);
p = lq->front;
}
free(lq);
lq = NULL;
return lq;
}
main函数
#include <stdio.h>
#include <stdlib.h>
#include "linkqueue.h"
static int test();
int main()
{
printf("Mian start:\n");
test();
return 0;
}
static int test(){
linkqueue *lq;
lq = queue_create();
if(lq == NULL){
return -1;
}
enqueue(lq,9);
enqueue(lq,19);
enqueue(lq,29);
enqueue(lq,39);
enqueue(lq,49);
queue_clear(lq);
while (!queue_empty(lq))
{
printf("dequeue:%d\n",dequeue(lq));
}
lq = queue_free(lq);
return 0;
}