无头单向链表的实现:
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,863,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