单链表优点:动态结构,整个空间可以多个链表共用
不需要预先分配空间
插入删除方便
缺点:指针占用额外的空间,不能随机查找
==============list.h========================
#ifndef LIST_H__
#define LIST_H__
#define SIZE 32
typedef struct _datatype
{
int id;
char name[SIZE];
int math;
int chinese;
}datatype;
typedef struct node_st{
datatype data;
struct node_st *next;
}list;
int list_destroy(list *);
void list_display(list *);
int list_insert(list **, datatype *);
int list_delete(list **);
datatype *list_find(list *,int );
#endif
===========list.c=======================
#include"list.h"
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
void list_display(list *me)
{
list *cur;
for (cur = me; cur!=NULL; cur = cur->next)
{
printf("%d %s %d %d\n",cur->data.id, cur->data.name, cur->data.math, cur->data.chinese);
}
return ;
}
int list_destroy(list *me)
{
list * save = NULL;
while(me)
{
save = me->next;
free(me);
me = save;
}
return 0;
}
int list_insert(list **me, datatype *data)
{
list *new;
new = malloc(sizeof(*new));
if (NULL == new)
return -1;
new->data = *data;
new->next = *me;
*me = new;
return 0;
}
int list_delete(list **me)
{
if(NULL == *me)
return -1;
list *save;
save = *me;
*me = (*me)->next;
free(save);
return 0;
}
datatype *list_find (list *me, int id)
{
list *save;
for (save = me;save!=NULL;save = save->next)
{
if( save->data.id ==id)
{
return &save->data;
}
}
return NULL;
}
===============main.c==========================
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include"list.h"
int main()
{
list *list = NULL;
datatype tmp;
int i;
for (i = 0; i <7 ; i++)
{
tmp.id = i;
snprintf(tmp.name, SIZE, "stu%d",i);
tmp.math = rand()%100;
tmp.chinese = rand()%100;
list_insert(&list, &tmp);
}
list_display(list);
list_delete(&list);
printf("=============\n");
list_display(list);
datatype *prt;
prt = list_find(list,3);
if(prt==NULL)
printf("can't find\n");
else
printf("find it\n");
list_destroy(list);
return 0;
}