这里进行链表的测试:
1)测试函数:
int lst_test(void)
{
int i;
list *head, *new;
printf("%s begin:\n", __func__);
for (i = 0; i < LST_COUNT; i++)
{
if (i == 0)
{
head = create();
head->p_data = (int *)malloc(sizeof(int));
*((int *)(head->p_data)) = 0;
continue;
}
new = (list*)malloc(sizeof(list));
if (new == NULL)
{
perror("alloc list node error!\n");
return -1;
}
new->p_data = (int *)malloc(sizeof(int));
if (1 == g_perf_on)
{
if (i < 20)
*((int *)(new->p_data)) = rand() % 1000;
else
*((int *)(new->p_data)) = 899777;
}
else
{
*((int *)(new->p_data)) = rand() % LST_COUNT;
}
add_tail(head, new);
}
//print out list;
if (LST_COUNT <= 100)
print_lst(head);
//delete one node;
//int value = 4;
//del_node(head, (void *)(&value));
//add node;
/*
int dat0 = 8, dat1 = 1000;
printf("add node:\n");
add_node(head, (void *)&dat0, (void *)&dat1);
//*/
//sort list;
///*
if ( 1 == g_perf_on )
{
sort_lst(head, 0);
if (LST_COUNT <= 100)
{
printf("sorted list 0:\n");
print_lst(head);
}
printf("sorted list -1:\n");
sort_lst(head, -1);
if (LST_COUNT <= 100)
print_lst(head);
}
//*/
//reverse list;
//reverse_lst(&head);
//print_lst_from_tail(head);
free_lst(head);
printf("%s end!\n", __func__);
return 0;
}
2)主函数及其它相关函数:
void usage(const char *str)
{
printf("\n\tUsage:\n");
printf("\t%s [-p | [ -p --count <N>]]\n", str);
printf("\tExample:\n");
printf("\t%s\n", str);
printf("\tprint random array of data stored in the list;\n");
printf("\t%s -p\n", str);
printf("\tbubble sort performance testing;\n");
printf("\t%s -p --count <N>\n", str);
printf("\tbubble sort performance testing, the list has N nodes;\n");
printf("\n");
}
//Linux/Unix平台可以使用系统函数getopt(),详细请使用man 3 getopt;
int parse_args(int cnt, char **pptr)
{
if (cnt == 1)
{
return 1;
}
else if (cnt == 2)
{
if ( 0 == strncmp("-p", pptr[1], strlen("-p")) )
{
g_perf_on = 1;
return 1;
}
else
{
perror("argument error!\n");
return -1;
}
}
else if (cnt == 4)
{
if ( 0 == strncmp("-p", pptr[1], strlen("-p") ) && \
0 == strncmp("--count", pptr[2], strlen("--count")) )
{
LST_COUNT = atoi(pptr[3]);
if (LST_COUNT > 0)
{
g_perf_on = 1;
return 1;
}
else
{
return -1;
}
}
}
}
int main(int argc, char *argv[])
{
if (argc != 1 && argc != 2 && argc != 4)
{
usage(argv[0]);
return 1;
}
//parse arguments;
if ( -1 == parse_args(argc, argv) )
{
printf("arguments not correct!\n");
usage(argv[0]);
return -1;
}
printf("list node count: %d\n", LST_COUNT);
lst_test();
return 0;
}
至此, 粗略地实现了双向链表。
完整代码下载请参考我的资源:双向链表的实现