对于下面的链表声明,
#include <stdlib.h>
#include <stdio.h>
typedef struct list
{
int val;
struct list *next;
} list;
void destroy (list *l)
{
if (l)
{
destroy (l->next);
free (l);
}
}
为什么以下主要工作
int main()
{
list *test;
list *ptr1, *ptr2;
int i;
test = malloc (sizeof (list));
test->val = 0;
ptr2 = test;
for (i = 1; i <= 10; i++)
{
ptr1 = (list *) malloc (sizeof (list));
ptr1->val = i;
ptr2->next = ptr1;
ptr2 = ptr1;
}
ptr1 = test;
while (ptr1)
{
printf ("%d\n", ptr1->val);
ptr1 = ptr1->next ;
}
destroy (test);
return 0;
}
而这个甚至没有创建一个列表(它只创建一个节点)?
int main()
{
list *test;
list *ptr;
int i;
test = malloc (sizeof (list));
test->val = 0;
ptr = test->next;
for (i = 1; i <= 10; i++)
{
ptr = (list *) malloc (sizeof (list));
ptr->val = i;
ptr = ptr->next;
}
ptr = test;
while (ptr)
{
printf ("%d\n", ptr->val);
ptr = ptr->next ;
}
destroy (test);
return 0;
}
他们不使用相同的逻辑吗?