创建双向链表的一个陷阱!!

下面是一个创建双向链表的函数,你能看出来它的一个致命错误吗?

 1 Node *create()
 2 {
 3     ElemType data;
 4     Node *head,*p,*s;
 5     head=(Node*)malloc(sizeof(Node));
 6     head->before=NULL;
 7     p=head;
 8     cout<<"input data,type 0 to stop input"<<endl;
 9     while(1)
10     {
11         cin>>data;
12         if(data==0)
13         {
14             p->next=NULL;
15             break;
16         }
17         s=(Node*)malloc(sizeof(Node));
18         s->data=data;
19         p->next=s;
20         s->before=p;
21         p=s;
22     }
23     head=head->next;
24     
25     return head;
26 }

答案:在23行,头指针head被赋以新的值之后,head->before指向了原来的head结点,而原来的head结点并没有存储数据,也不等于NULL,所以下面在使用head->before是就会出现致命错误,并且很难检查出来

指针功能很强大,但使用时要万分小心!

修改后的代码

 1 Node *create()
 2 {
 3     ElemType data;
 4     Node *head,*p,*s;
 5     head=(Node*)malloc(sizeof(Node));
 6     p=head;
 7     cout<<"input data,type 0 to stop input"<<endl;
 8     while(1)
 9     {
10         cin>>data;
11         if(data==0)
12         {
13             p->next=NULL;
14             break;
15         }
16         s=(Node*)malloc(sizeof(Node));
17         s->data=data;
18         p->next=s;
19         s->before=p;
20         p=s;
21     }
22     head=head->next;
23     head->before=NULL;
24     return head;
25 }
原文地址:https://www.cnblogs.com/xmkk/p/3290893.html