7.10 队列:链式队列
空间不连续
单向链表
代码
/*************************************
* 名称描述:队列:使用链表实现
* 实现功能:队列的出队、入队、队列判断、置空队列等
* 作 者:王 利 涛
* QQ 群 :475504428
* 公 众 号:宅学部落(armlinuxfun)
* 嵌入式自学路线咨询 QQ:3284757626
*************************************/
#include<stdio.h>
#include<stdlib.h>
struct list_node{
int data;
struct list_node *next;
};
struct queue{
struct list_node *front;
struct list_node *rear;
};
int is_queue_empty(struct queue *q)
{
return (q->front==NULL || q->rear==NULL);
}
int enqueue(struct queue *q, int value)
{
struct list_node *p =(struct list_node *)malloc(sizeof(struct list_node));
if(p==NULL)
{
printf("malloc list_node failed!\n");
return -1;
}
p->data = value;
p->next = NULL;
if(q->rear == NULL) //q队列为空的时候,入队操作q队列的队头和队尾都指向q
q->front = q->rear = p;
else
{
q->rear->next = p; //p结点入队
q->rear = p; //q队列的尾部指向p结点
}
return 0;
}
struct list_node *dequeue(struct queue *q)
{
struct list_node *p;
if(q->front == NULL)
{
printf("Empty queue!\n");
return (struct list_node *)-1;
}
p = q->front;
if(q->front->next == NULL) //队列的第二个结点为空
q->front = q->rear = NULL;
else
q->front = q->front->next; //队头指向第二个结点
return p; //return 队尾结点
}
void clear_queue(struct queue *q)
{
struct list_node *p;
if(q->front == NULL)
{
printf("Empty queue!\n");
free(q);
}
p = q->front;
while(p != NULL)
{
q->front = q->front->next;
free(p); //释放结点
p = q->front;
}
free(q);
}
int print_queue(struct queue *q)
{
struct list_node *p;
if(q==NULL)
{
printf("no queue!\n");
return -1;
}
p = q->front;
while(p != NULL)
{
printf("%d\n",p->data);
p = p->next;
}
return 0;
}
void init_queue(struct queue *q)
{
q->front = NULL;
q->rear = NULL;
}
int main(void)
{
struct queue *q =(struct queue *)malloc(sizeof(struct queue));
init_queue(q);
struct list_node *node;
enqueue(q,1);
enqueue(q,2);
print_queue(q);
node = dequeue(q);
free(node);
print_queue(q);
node = dequeue(q);
free(node);
print_queue(q);
enqueue(q,3);
enqueue(q,4);
enqueue(q,5);
enqueue(q,6);
enqueue(q,7);
enqueue(q,8);
enqueue(q,9);
enqueue(q,10);
print_queue(q);
node = dequeue(q);
print_queue(q);
clear_queue(q);
return 0;
}