前两节,我们已经完成了链表的一些操作,快来测试一下吧。
这里使用的单元测试工具名字叫“check”。
START_TEST(my_slist_1) { struct student students[8] = {{"WangDong",18},{"LiuMing",19},{"SunYazhou",21},{"ChenYu",27},{"LiuXuewei",28},\ {"ZhangGuorong",47},{"LiuDehua",53},{"WangGuozhen",48}}; struct slist_info list; slist_init(&list); int i = 0; for(;i<sizeof(students)/sizeof(students[0]);++i) list.insert_head(students+i,&list); list.for_each(&list,print_student);
我们先定义了一个数组,里面存放了姓名,年龄。接下来定义一个链表,并初始化。然后调用插入方法,依次插入。遍历一下,打印出来:
void print_student(void *data) { struct student *p = data; printf("Name: %15s Age:%d\n",p->name,p->age); }
用到了这个回调函数。看看打印的结果:
Name: WangGuozhen Age:48
Name: LiuDehua Age:53
Name: ZhangGuorong Age:47
Name: LiuXuewei Age:28
Name: ChenYu Age:27
Name: SunYazhou Age:21
Name: LiuMing Age:19
Name: WangDong Age:18
struct node_info *p = list.find(&list,compare_student,&students[3]); list.del(p,&list); list.for_each(&list,print_student);
比较的回调函数是:
int compare_student(void *dest,void *src) { struct student *p1 = dest; struct student *p2 = src; if(strcmp(p1->name,p2->name)==0) return 1; else return 0; }
结果如图:
Name: WangGuozhen Age:48
Name: LiuDehua Age:53
Name: ZhangGuorong Age:47
Name: LiuXuewei Age:28
Name: SunYazhou Age:21
Name: LiuMing Age:19
Name: WangDong Age:18
再测试一下反转:
list.invert(&list); list.for_each_safe(&list,print_student); } END_TEST
Name: WangDong Age:18
Name: LiuMing Age:19
Name: SunYazhou Age:21
Name: LiuXuewei Age:28
Name: ZhangGuorong Age:47
Name: LiuDehua Age:53
Name: WangGuozhen Age:48
测试成功!