栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

队列——C语言(链表)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

队列——C语言(链表)

用链表来写队列真的比数组简单得多,本人已经发了用数组实现队列的文章,欢迎大家阅览

1.先写一个队列的接口(queue.h)
#include 

#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);
2.再写一个文件具体实现链式队列函数操作(l_queue.c)
#include "queue.h"
#include 
#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;
}
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,尾元素为%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!!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/920365.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号