用链表来写队列真的比数组简单得多,本人已经发了用数组实现队列的文章,欢迎大家阅览
1.先写一个队列的接口(queue.h)
/*
一个队列模块的接口
*/
#include <stdlib.h>
#define QUEUE_TYPE int /*队列元素的类型*/
/*
** create_queue
** 创建一个队列,参数为队列可以存储元素的最大数量
** 这个函数只适用于动态分配数组的队列版本
*/
void create_queue(size_t size);
/*
** destroy_queue
** 销毁一个队列,只适用于链式和动态分配数组的版本
*/
void destroy_queue(void);
/*
** insert
** 向队列添加一个新元素,参数为要添加的元素
*/
void insert(QUEUE_TYPE value);
/*
** delete
** 从队列中移除一个元素
*/
void delete(void);
/*
** first
** 返回队列中第一个元素的值,队列不动
*/
QUEUE_TYPE first(void);
/*
** last
** 返回队列最后一个元素的值,队列不动
*/
QUEUE_TYPE last(void);
/*
** is_empty
** 如果队列为空,返回1,否则返回0
*/
int is_empty(void);
/*
** is_full
** 如果队列为满,返回1,否则返回0
*/
int is_full(void);
/*
** aqueue_print
** 遍历打印队列(数组版本),并返回队列存储元素个数
*/
int aqueue_print(void);
/*
** lqueue_print
** 遍历打印队列(链表版本),并返回队列存储元素个数
*/
int lqueue_print(void);
2.再写一个文件具体实现链式队列函数操作(l_queue.c)
/*
** 用链表实现队列
** 该链表有一个头指针,一个尾指针
** 当队列只有一个元素时,头尾指针指向同一结点
*/
#include "queue.h"
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <malloc.h>
/*定义链表结点*/
typedef struct NODE{
QUEUE_TYPE value;
struct NODE *next;
}Node;
/*定义头尾指针*/
static Node *front = NULL;
static Node *rear = NULL;
/*
** destroy_queue
*/
void destroy_queue(void){
front = NULL;
rear = NULL;
}
/*
** insert
*/
void insert(QUEUE_TYPE value){
Node *new = malloc(sizeof(QUEUE_TYPE));
assert(new != NULL);
new->value = value;
new->next = NULL;
//如果队列为空
if(front == NULL && rear == NULL){
front = new;
rear = new;
}else{
rear->next = new;
rear = rear->next;
}
}
/*
** delete
*/
void delete(void){
if(front == rear){
front = NULL;
rear = NULL;
}else
front = front->next;
}
/*
** first
*/
QUEUE_TYPE first(void){
return front->value;
}
/*
** last
*/
QUEUE_TYPE last(void){
return rear->value;
}
/*
** is_empty
*/
int is_empty(void){
return front == NULL && rear == NULL;
}
/*
** is_full
*/
int is_full(void){
return 0;
}
/*
** lqueue_print
** 遍历打印队列(链表版本),并返回队列存储元素个数
*/
int lqueue_print(void){
Node *find = front;
int count = 0;
while(find != NULL){
printf("%d", find->value);
++count;
if((find = find->next)!=NULL)
printf(", ");
}
return count;
}
3.最后写一个测试主函数(l_main.c)
#include "l_queue.c"
int main(){
insert(33);
insert(22);
insert(44);
insert(55);
insert(66);
printf("\n该队列存储了%d个元素",lqueue_print());
printf("\n队列头元素为%d,尾元素为%d\n\n", first(), last());
delete();
delete();
printf("\n该队列存储了%d个元素",lqueue_print());
printf("\n队列头元素为%d,尾元素为%d\n\n", first(), last());
return 0;
}
控制台输出:
33, 22, 44, 55, 66
该队列存储了5个元素
队列头元素为33,尾元素为66
44, 55, 66
该队列存储了3个元素
队列头元素为44,尾元素为66
总结:到此,我已经用数组,链表实现了队列,发现队列用链表真的比用数组方便简洁的多,我之前还写了堆栈的实现,也是分别用数组和链表来实现,大家有兴趣可以去看看我之前的文章,谢谢大家!C语言yyds!!