往链表中插入一项时,如果指针使用不慎,容易造成错误。下面先看一段正确的代码:代码的功能是:往一个空链表中插入三项,每一项的元素分别是0,1,2。
#include <stdio.h>
#include <stdlib.h>
typedef struct _Node
{
int elem;
struct _Node *next;
}Node;
int main()
{
Node *list = NULL;
Node *tail = NULL;
for (int i=0; i<3; i++)
{
Node *p = (Node *)malloc(sizeof(Node));
p->elem = i;
if (list == NULL)
{
list = p;
tail = list;
}
else
{
tail->next = p;
tail = tail->next;
}
}
for (Node *p=list; p!=NULL; p=p->next)
{
printf("%d/n", p->elem);
}
return 0;
}
下面再看错误代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct _Node
{
int elem;
struct _Node *next;
}Node;
int main()
{
Node *list = NULL;
Node *tail = NULL;
for (int i=0; i<3; i++)
{
Node *p = (Node *)malloc(sizeof(Node));
p->elem = i;
if (list == NULL)
{
list = p;
tail = list->next;
}
else
{
tail = p;
tail = tail->next;
}
}
for (Node *p=list; p!=NULL; p=p->next)
{
printf("%d/n", p->elem);
}
return 0;
}
红色加粗标记的代码是与正确代码不同的部分,错误的原因是:在 tail = list->next 的时候,list->next 本身就为NULL,所以导致tail 的指向也是不明确的。
总结一下,这种往链表中插入一项的情况下,给指针赋值时,一定赋的是确定的一项,而不能是NULL。
在回看代码,也就是说,tail一定要指向list的最后一项,而不能指向最后一项的下一项。