Linux下学C语言——第十八节 数据结构|无头单向链表

无头单向链表的实现:

nohead.h:

#ifndef NOHEAD_H__
#define NOHEAD_H__

#define NAMESIZE 32

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

typedef struct node_st
{
    score data;
    struct node_st *next;
}nohead;


nohead *list_insert(nohead *,score *);

void list_show(nohead *);
int list_delete(nohead **);

nohead *list_find(nohead *,int);

void list_destroy(nohead *);
#endif

nohead.c:

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



nohead  *list_insert(nohead *list,score *data)
{
    nohead *new;
    
    new = malloc(sizeof(*new));
    if(new == NULL)
        return NULL; 
        
    new->data = *data;
    //new->next = NULL;
    
    new->next = list;
    list = new;
      
    return list; 
}

void list_show(nohead *list)
{
    nohead *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(nohead **list)
{
    nohead *cur;
    if(*list == NULL)
        return -1;

    cur = *list;
    *list = (*list)->next;

    free(cur);
    return 0;
}

nohead *list_find(nohead *list,int id)
{
    nohead * cur;
    cur = NULL;

    for(cur = list; cur != NULL;cur = cur ->next)
    {
        if(cur ->data.id == id)
        {
            return cur;
        }
    }

    return NULL;
}

void list_destroy(nohead * list)
{
    nohead *cur;
    if(list == NULL)
        return ;

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

    }
}

main.c:

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

#include "nohead.h"

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

       list =  list_insert(list,&tmp);
    printf("m======\n");
    }

    list_show(list);
    printf("\n");

    nohead *ptr;
    ptr = list_find(list,3);
    if(ptr == NULL)
        printf("Can not find \n");
    else 
        printf("%d,%s,%d,%d\n",ptr->data.id,ptr->data.name,ptr->data.math,ptr -> data.chinese);
    printf("\n");
    
    list_delete(&list);
    list_show(list);
    
    list_destroy(list);
}

makefile

all:main

main:main.o nohead.o
    $(CC) $^ -o $@

clean:
    rm *.o main -rf

终端执行:

6,stu6,90,59
5,stu5,62,27
4,stu4,49,21
3,stu3,86,92
2,stu2,93,35
1,stu1,77,15
0,stu0,83,86

3,stu3,86,92

5,stu5,62,27
4,stu4,49,21
3,stu3,86,92
2,stu2,93,35
1,stu1,77,15
0,stu0,83,86

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值