用链表来写队列真的比数组简单得多,本人已经发了用数组实现队列的文章,欢迎大家阅览
1.先写一个队列的接口(queue.h)#include2.再写一个文件具体实现链式队列函数操作(l_queue.c)#define QUEUE_TYPE int void create_queue(size_t size); void destroy_queue(void); void insert(QUEUE_TYPE value); void delete(void); QUEUE_TYPE first(void); QUEUE_TYPE last(void); int is_empty(void); int is_full(void); int aqueue_print(void); int lqueue_print(void);
#include "queue.h" #include3.最后写一个测试主函数(l_main.c)#include #include #include typedef struct NODE{ QUEUE_TYPE value; struct NODE *next; }Node; static Node *front = NULL; static Node *rear = NULL; void destroy_queue(void){ front = NULL; rear = NULL; } 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; } } void delete(void){ if(front == rear){ front = NULL; rear = NULL; }else front = front->next; } QUEUE_TYPE first(void){ return front->value; } QUEUE_TYPE last(void){ return rear->value; } int is_empty(void){ return front == NULL && rear == NULL; } int is_full(void){ return 0; } 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; }
#include "l_queue.c"
int main(){
insert(33);
insert(22);
insert(44);
insert(55);
insert(66);
printf("n该队列存储了%d个元素",lqueue_print());
printf("n队列头元素为%d,尾元素为%dnn", first(), last());
delete();
delete();
printf("n该队列存储了%d个元素",lqueue_print());
printf("n队列头元素为%d,尾元素为%dnn", first(), last());
return 0;
}
控制台输出:
33, 22, 44, 55, 66 该队列存储了5个元素 队列头元素为33,尾元素为66 44, 55, 66 该队列存储了3个元素 队列头元素为44,尾元素为66
总结:到此,我已经用数组,链表实现了队列,发现队列用链表真的比用数组方便简洁的多,我之前还写了堆栈的实现,也是分别用数组和链表来实现,大家有兴趣可以去看看我之前的文章,谢谢大家!C语言yyds!!



