#include <stdio.h>
#include <malloc.h>
struct student
{
int num;
char name[10];
struct student *next;
};
void main()
{ void print(struct student *head);
struct student *creat();
struct student *solve(struct student *head_a,struct student *head_b);
struct student *head,*head_a,*head_b;
head_a=creat();
head_b=creat();
head=solve(head_a,head_b);
print(head);
}
struct student *creat()
{
struct student *head,*p,*p1;
p1=(struct student *)malloc(sizeof(struct student));
head=p=p1;
printf("输入学号和姓名0停止接收数据\n");
printf("请输入学生学号和姓名:");
scanf("%d %s",&p->num,&p->name);
while(p->num!=0)
{
printf("请输入学生学号和姓名:");
p1->next=p;
p1=p;
p=(struct student *)malloc(sizeof(struct student));
scanf("%d %s",&p->num,&p->name);
}
p1->next=NULL;
return head;
}
struct student *solve(struct student *head_a,struct student *head_b)
{
struct student *p,*p1,*t;
p=p1=head_a;
t=head_b;
while(p!=NULL)
{
t=head_b;
while(t->next!=NULL&&(t->num!=p->num))
{
t=t->next;
}
if(t->num==p->num)
{
if(p==head_a)
{
head_a=head_a->next;
p1=p=head_a;
}
else
{
p1->next=p->next;
p=p->next;
}
}
else
{
p1=p;
p=p->next;
}
}
return head_a;
}
void print(struct student *head)
{
struct student *p;
while(p!=NULL)
{
printf("%d %s\n",p->num,p->name);
p=p->next;
}
}
帮我看看我哪里写错了。。。。。答的好有追加~
【1】那里不是特明白...creat那里为什么要head=NULL呢,然后下面依然head=p...不是等于前面白赋值了么..直接就把print函数里面*p初始化不就可以运行成功了吗....望解答..谢谢~
追答【1】里面说的很清楚了啊!
你原来的 creat 函数中认为链表是有一个表头节点的,也就是链表的第一节点是 head->next,
而不是 head。
但是下面的 solve 函数和 print 函数都认为链表是没有表头节点的,也就是他们认为链表的
第一个节点是:head 而不是 head->next 。
这两个是有矛盾的,两个地方要修改一个地方,这里是修改了 creat 函数。
head=NULL 是初始化为一个空的链表,比如 第一就输入: 0 0 ,
那么 while(!(p->num == 0 && strcmp(p->name,"0")==0)) 这个循环里面的语句都不会执行,
head 就应该是 NULL 。
while((pb!=NULL)&&(pa->num != pb->num))
//这里应该是while((pb->next!=NULL)&&(pa->num != pb->num))
不然b链表循环到最后一个元素的时候如果这个元素不跟a链表当中有相同学号,那么依然会执行pb=pb->next; 使得pb指向空指针;
紧接着你下面的判断语句if(pa->num==pb->num) 这个时候PB指向空地址,读取不出pb->num这个值,就会报错
head->next=NULL;//修改地点:很重要。
为什么很重要?