#include<stdio.h>
#include<time.h>
#define?ElemType?int?
struct?node
{
????ElemType?data;
????struct?node?*?next;
};
typedef?struct?node?NODE;
NODE?*?CreateLinkList(int?n)
{
int?i;
????NODE?*p,*q;
ElemType?a;
q=(NODE?*)malloc(sizeof(NODE));
????a=rand()%20;
????q->data?=?a;
q->next=NULL;
for(i=n-1;i>=1;i--)
????{
????p=(NODE?*)malloc(sizeof(NODE));
????a=rand()%20;
????????p->data=a;
???? p->next=q;????????
????????q=p;
}
????return?q;
}
NODE?*?InsertLinkList(NODE?*?head,ElemType?x,ElemType?y)
{
????NODE?*s,*p,*q;
s=(NODE?*)malloc(sizeof(NODE));
s->data=y;
s->next=NULL;
????for(p=head;p!=NULL;p=p->next)
????printf("%d\n",p->data);?
printf("\n");
????if(head==NULL)
head=s;
else?if?(head->data?==?x)
{
????s->next?=?head;
????head?=?s;
}
????else
????{
????q=head;
????p=head->next;?
while(p!=NULL&&p->data!=x) {
????q=p;
????p=p->next;
}
if(p->data==x)
{
????s->next=p;
????q->next?=?s;
}
else
{
q->next=s;
}
}
????return?head;
}
void?main()
{
????ElemType?a;
NODE?*?head,*p;
????srand((unsigned)time(NULL));
????head=CreateLinkList(10);
????for(p=head;p!=NULL;p=p->next)
????printf("%d\n",p->data);
printf("%10d\n",a=rand()%20);
head=InsertLinkList(head,a,99);
????for(p=head;p!=NULL;p=p->next)
????printf("%d\n",p->data);
}程序初步調(diào)試,發(fā)現(xiàn)InsertLinkList函數(shù)的while循環(huán)里出錯,但不知道具體哪里錯誤。求牛人解決
1 回答

泡面大減價
TA貢獻1條經(jīng)驗 獲得超1個贊
問題已解決:
當p==NULL,(第2頁第6行)if中條件p->data==x訪問了p->data,而當p==NULL,訪問是非法的。
修改方案:條件p->data==x成立說明p!=NULL,把條件改為p!=NULL即可
- 1 回答
- 0 關(guān)注
- 1213 瀏覽
添加回答
舉報
0/150
提交
取消