# include <stdio.h>
# include <stdlib.h>
# define DATATYPE int
typedef struct node{
DATATYPE data;
struct node *next;
}linkqueue;
typedef struct{
linkqueue *front,*rear;
int len;
}LINKQUEUE;
void init_linkqueue(LINKQUEUE *Lq)
{
linkqueue *p = (linkqueue*)malloc(sizeof(linkqueue));
p->next = NULL;
Lq->front = Lq->rear = p;//此时的Lq->front域并未malloc,此时的Lq->front内部为NULL,切记不可用Lq->front->next=p;
}
int isEmpty(LINKQUEUE *Lq)
{
int isEmpty = 0;
if(Lq->front==Lq->rear)
isEmpty = 1;//为空队列
return isEmpty;
}
void add_linkqueue(LINKQUEUE *Lq,DATATYPE n)
{
linkqueue *p = (linkqueue*)malloc(sizeof(linkqueue));
p->data = n;
p->next = NULL;
Lq->rear->next = p;
Lq->rear = p;
Lq->len++;
}
DATATYPE del_linkqueue(LINKQUEUE *Lq)
{
if(isEmpty(Lq))
{
printf("linkqueue empty!\n");
return;
}
linkqueue *q = Lq->front;//记录下,方便释放
DATATYPE data = q->next->data;
linkqueue *p = q->next;//记录要释放的区域
q->next = q->next->next;
Lq->rear = q->next;
free(p);
Lq->len--;
return data;
}
DATATYPE getHead_linkqueue(LINKQUEUE *Lq)
{
if(isEmpty(Lq))
{
printf("linkqueue empty!\n");
return;
}
DATATYPE headData = Lq->front->next->data;
return headData;
}
int main()
{
LINKQUEUE *Lq = (LINKQUEUE*)malloc(sizeof(LINKQUEUE));
init_linkqueue(Lq);
int i = 0;
for(i;i<10;i++)
{
add_linkqueue(Lq,i);
}
printf("length:%d\n",Lq->len);
for(i = 0;i<10;i++)
{
printf("del_queue%d:%d\n",i,del_linkqueue(Lq));//先进先出
}
printf("delete after length:%d\n",Lq->len);
}
c语言:队列的链式存储结构
最新推荐文章于 2023-04-12 21:55:21 发布