目录
test.c
#include <stdio.h>
#include "linkqueue.h"
int main(int argc, const char *argv[])
{
linkqueue *lq;
lq = queue_create();
if (lq == NULL)
return -1;
enqueue(lq, 10);
enqueue(lq, 20);
enqueue(lq, 30);
enqueue(lq, 40);
//while (!queue_empty(lq)) {
//printf("dequeue:%d\n", dequeue(lq));
//}
queue_clear(lq);
lq = queue_free(lq);
enqueue(lq, 50);
return 0;
}
linkqueue.c
#include <stdio.h>
#include <stdlib.h>
#include "linkqueue.h"
linkqueue * queue_create()
{
linkqueue *lq;
if ((lq = (linkqueue*)malloc(sizeof(linkqueue))) == NULL)
{
printf("malloc linkqueue is default");
return NULL;
}
if ((lq->front = lq->rear = (linklist)malloc(sizeof(listnode))) == NULL)
{
printf("malloc lq->rear&lq->front is default");
return NULL;
}
lq->front->next = NULL;
lq->front->data = 0;
//lq->rear = lq->front;
return lq;
}
int enqueue(linkqueue *lq, datatype x)
{
linklist p;
//p->fr = (linkqueue*)malloc(sizeof(linkqueue));
if (lq == NULL) {
printf("lq is NULL\n");
return -1;
}
if ((p = (linklist)malloc(sizeof(listnode))) == NULL) {
printf("malloc node failed\n");
return -1;
}
p->data = x;
p->next = NULL;
lq->rear->next = p;
lq->rear = p;
//lq->rear->data = x;
return 0;
}
datatype dequeue(linkqueue *lq)
{
linklist p;
datatype x;
if(lq == NULL)
{
printf("lq is NULL");
return -1;
}
p = lq->front;
lq->front = lq->front->next;
free(p);
p = NULL;
x = lq->front->data;
return x;
}
int queue_empty(linkqueue *lq)
{
if(lq == NULL)
{
printf("lq is NULL");
return -1;
}
return (lq->front == lq->rear ? 1 : 0);
}
#if 1
int queue_clear(linkqueue *lq)
{
linklist p;
if(lq == NULL)
{
printf("lq is NULL");
return -1;
}
for(;lq->front != lq->rear;)
{
p = lq->front;
lq->front = lq->front->next;
printf("clear free:%d\n", p->data);
free(p);
p = NULL;
}
return 0;
}
#endif
#if 0
int queue_clear(linkqueue *lq) {
linklist p;
if (lq == NULL) {
printf("lq is NULL\n");
return -1;
}
while (lq->front->next) {
p = lq->front;
lq->front = p->next;
printf("clear free:%d\n", p->data);
free(p);
p = NULL;
}
return 0;
}
#endif
#if 0
linkqueue * queue_free(linkqueue *lq) {
linklist p;
if (lq == NULL) {
printf("lq is NULL\n");
return NULL;
}
while (lq->front) {
p = lq->front;
lq->front = p->next;
printf("free:%d\n", p->data);
free(p);
}
free(lq);
lq = NULL;
return NULL;
}
#endif
#if 1
linkqueue * queue_free(linkqueue *lq)
{
linklist p;
if(lq == NULL)
{
printf("lq is NULL");
return NULL;
}
for(;lq->front != NULL;)
{
p = lq->front;
lq->front = lq->front->next;
printf("free:%d\n", p->data);
free(p);
p = NULL;
}
free(lq);
lq = NULL;
return NULL;
}
#endif
linkqueue.h
typedef struct node {
datatype data;
struct node *next;
}listnode , *linklist;
typedef struct {
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);