倒置链表。当for控制语句为 for (tmp = tmp->next; NULL != tmp->next;) 时,在最后一次循环总,tmp = tmp->next已经使得tmp指向NULL,再执行控制语句 NULL != tmp->next时,会产生段错误。 当控制语句为 for (tmp = tmp->next; NULL != tmp;)时,会产生段错误,不知何故,留待认知。 此处用while循环更合适。while (tmp)。
8) clear_list ()
SLINK clear_list (SLINK list)
{
NODE *cur = NULL;
for (list = list->next; NULL != list->next;)
{
cur = list;
list = list->next;
free (cur);
}
return list;
}
清空链表,执行后list->next指向NULL, 头节点仍在。
9) destroy_list ()
void destroy_list (SLINK *list)
{
NODE *cur = NULL;
for (*list = (*list)->next; NULL != (*list)->next;)
{
cur = *list;
*list = (*list)->next;
free (cur);
}
}
销毁链表,执行后list指向NULL,头节点不再。若destroy_list后执行clear_list,会导致段错误。
clear_list和destroy_list参数不同,导致结果不同。clear传入参数为链表指针,clear执行后链表指针执行·区域不变;依旧为头节点。destory传入参数为双重指针,执行后链表指针指向位置改变,设tailor为原链表最后一节点,则此时list = tailor->next,即:list = NULL。可类比交换函数swap (int a, int b)和swap (int *a, int *b)。
测试
#define i_track(n) printf ("The %s's is %d.\n", #n, (n))
#define s_track(n) printf ("%s.\n", #n);
int
main ( int argc, char *argv[] )
{
int elem = 0;
int len = 5;
SLINK list = header_generate ();
srand ((unsigned)time (0));
for (int i = 1; i <= len; i++)
{
elem = rand () % 100;
node_insert (list, elem, NULL);
}
dump_list (list);
s_track(reverse);
reverse_list (list);
dump_list (list);
s_track(pos);
int pos = 0;
scanf ("%d", &pos);
s_track(add);
int add = 0;
scanf ("%d", &add);
node_insert (list, add, &pos);
dump_list (list);
s_track(del);
int del;
scanf ("%d", &del);
node_delete (list, del);
dump_list (list);
destroy_list (&list);
clear_list (list);
return EXIT_SUCCESS;
}