Linux下学C语言——第十八节 数据结构

编程入门 行业动态 更新时间:2024-10-06 17:13:12

Linux下学C语言——第十八节 <a href=https://www.elefans.com/category/jswz/34/1769880.html style=数据结构"/>

Linux下学C语言——第十八节 数据结构

无头单向链表的实现:

nohead.h:

#ifndef NOHEAD_H__
#define NOHEAD_H__#define NAMESIZE 32typedef 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

更多推荐

Linux下学C语言——第十八节 数据结构

本文发布于:2024-02-28 02:15:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1767455.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据结构   语言   第十八节   Linux

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!