单向无头不循环链表
main.c
#include <stdio.h> #include <stdlib.h> #include "nohead.h" int main() { int i ; int ret ; struct node_st *list = NULL ; struct score_st tmp ; struct score_st *ptr ; for(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(ret != 0) exit(1); } list_delete(&list); list_show(list); ptr = list_find(list , 8); if(ptr == NULL) printf("Can not find "); else printf("%d %s %d %d ",ptr->id , ptr->name,ptr->math,ptr->chinese); list_destroy(list); exit(0); }
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(new == NULL) 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 ",cur->data.id , cur->data.name ,cur->data.math,cur->data.chinese); } } //首部删除 int list_delete(struct node_st **list) { struct node_st *cur ; if(*list == NULL) 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) { return &(cur->data); } } return NULL ; } void list_destroy(struct node_st *list) { struct node_st *cur ; if(list == NULL) return ; for(cur = list ; cur != NULL; cur = list) { list = cur->next ; free(cur); } return ; }
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 * list); int list_delete(struct node_st **list); struct score_st * list_find(struct node_st *list ,int id); void list_destroy(struct node_st *list); #endif
Makefile
all:main main:main.o nohead.o $(CC) $^ -o $@ clean: rm *.o main -rf