C语言高级进阶

链表是由一系列互相连接的节点组成的数据结构,这种数据结构非常有用,是实现队列和栈的基础。

学习内容

这一章我们继续单链表的学习,实现一个无头单链表的创建,插入,按值查找,显示以及销毁。代码来自于(B站)史上最强最细腻的linux嵌入式C语言学习教程【李慧芹老师】,需要学习的童鞋自行搜索观看,此处不多介绍。

学习产出

nohead.h

#ifndef __NOHEAD_H__
#define __NOHEAD_H__

#define NAMESIZE 32

struct score_st
{
    int id;
    char name[NAMESIZE];
    int math;
    int chinese;
};

struct node_st
{
    struct score_st data;
    struct node_st *next;
};

int list_insert(struct node_st **list,struct score_st *data);

void list_show(struct node_st*);


int list_delete(struct node_st **);

struct score_st * list_find(struct node_st *, int id);

void list_distroy(struct node_st *);


#endif /

nohead.c

#include <stdio.h>
#include <stdlib.h>
#include "nohead.h"

int list_insert(struct node_st **list, struct score_st *data)
{
    struct node_st *new;
    new = malloc(sizeof(*new));
    if(NULL == new)
    {
        return -1;
    }

    new->data = *data;
    new->next = *list;
    *list = new;

    return 0;

}

void list_show(struct node_st* list)
{
    struct node_st *cur;

    for(cur = list; cur != NULL; cur = cur->next)
    {
        printf("%d %s %d %d\n", cur->data.id, cur->data.name, cur->data.math, cur->data.chinese);
    }
}


int list_delete(struct node_st **list)
{
    struct node_st *cur;
    if(NULL == *list)
        return -1;
    cur = *list;
    *list = (*list)->next;

    free(cur);

    return 0;
}

struct score_st * list_find(struct node_st *list, int id)
{
    struct node_st *cur;
    for(cur = list; cur != NULL; cur = cur->next)
    {
        if(cur->data.id == id)
        {
//            printf("%d %s %d %d\n", cur->data.id, cur->data.name, cur->data.math, cur->data.chinese);
            return &cur->data;
        }
    }

    return ;

}

void list_distroy(struct node_st *list)
{
    struct node_st *cur;
    if(NULL == list)
    {
        return ;
    }

    for(cur = list; cur != NULL; cur = list)
    {
        list = cur->next;
        free(cur);
    }
}

main.c中进行测试

#include <stdio.h>
#include <stdlib.h>

#include "nohead.h"

int main()
{
    struct node_st *list = NULL;
    struct score_st tmp;
    int ret;

    for( int i = 0; i < 7; i++)
    {
        tmp.id = i;
        snprintf(tmp.name, NAMESIZE, "stu%d",i);
        tmp.math = rand()%100;
        tmp.chinese = rand()%100;

        ret = list_insert(&list, &tmp);
        if(0 != ret)
            exit(1);

    }

    list_show(list);

    printf("\n\n");

    list_delete(&list);

    list_show(list);

    printf("\n\n");

    int id = 3;
    list_find(list, id);
    printf("\n\n");

    id = 4;
    struct score_st *ptr;

    ptr = list_find(list, id);
    if(NULL == ptr)
        printf("Can not find!");
    else
        printf("%d %s %d %d\n", ptr->id, ptr->name, ptr->math, ptr->chinese);

    list_distroy(list);

    list_show(list);
    return 0;
}

更多推荐