有两个链表a和b,设结点中包含学号和姓名,从a链表中删除和b链表中相同学号的结点?为什么我这个程序没效果

2024-12-13 21:23:17
推荐回答(2个)
回答1:

给你改了del函数:
包括它的内容和其返回值,及其要主函数中的声明,改正后能运行:
#include
#include
#include
#define LEN sizeof(struct student)
int n;
struct student
{char num[10];
char name[10];
struct student *next;
}*ahead,*bhead;
main()
{struct student *creat(void);
struct student *del(struct student *ahead,struct student *bhead);//改正返回值
void print(struct student *ahead);
ahead=creat();
bhead=creat();
ahead=del(ahead,bhead);
print(ahead);
}
struct student *creat(void)
{
struct student *p1,*p2,*head;
n=0;
p1=p2=(struct student *)malloc(LEN);
scanf("%s %s",p1->num,p1->name);
head=NULL;
while(strcmp(p1->num,"0")!=0)
{n=n+1;
if(n==1) head=p1;
else p2->next=p1;
p2=p1;
p1=(struct student *)malloc(LEN);
scanf("%s %s",p1->num,p1->name);
}
p2->next=NULL;
return(head);
}
struct student *del(struct student *ahead,struct student *bhead)//返回值不能为void,这个函数里面改得多,注意理解和比较,打//的地方修改,注意!
{
struct student *p,*ap1,*bp1;
p=ap1=ahead;//
while(ap1)//
{
bp1=bhead;
while(bp1)//
{
if(strcmp(bp1->num,ap1->num)==0)//
{
if(ap1==ahead)
ahead=ap1->next;
else//
{
p->next=ap1->next;
ap1=p->next;
}
break;//
}
bp1=bp1->next;
}
if(bp1==NULL)//
{
p=ap1;
ap1=ap1->next;
}
}
return ahead;//
}
void print(struct student *ahead)
{struct student *p;
p=ahead;
while(p!=NULL)
{printf("%s %s\n",p->num,p->name);
p=p->next;
}
}

回答2:

根据@121446881的回答修改自己的代码

#include 
#include
#include

struct Student
{
char num[10];
char name[8];
struct Student *next;
};

//输出函数
void print(struct Student *stu)
{
struct Student *p;
//将头节点的指针给予临时节点p
p = stu;
if (stu != NULL)
{
do
{
printf("学号:%s,姓名:%s\n", p->num, p->name);
p = p->next;
} while (p != NULL);
}
}

struct Student *del(struct Student *ahead, struct Student *bhead) //返回值不能为void,这个函数里面改得多,注意理解和比较,打//的地方修改,注意!
{
struct Student *p, *ap1, *bp1;
p = ap1 = ahead; //
while (ap1)      //
{
bp1 = bhead;
while (bp1) //
{
if (strcmp(bp1->num, ap1->num) == 0) //
{
if (ap1 == ahead)
ahead = ap1->next;
else //
{
p->next = ap1->next;
ap1 = p->next;
}
break; //
}
bp1 = bp1->next;
}
if (bp1 == NULL) //
{
p = ap1;
ap1 = ap1->next;
}
}
return ahead; //
}
int chapter9_11()
{
struct Student stu1[L1] = {{"34101", "aaa"}, {"34102", "bbb"}, {"34103", "ccc"}, {"34104", "ddd"}};
struct Student stu2[L2] = {{"34105", "eee"}, {"34106", "fff"}, {"34103", "ccc"}, {"34104", "ddd"}, {"34107", "ggg"}};
struct Student *head1, *head2;
// 链表1的头指针
head1 = stu1;
// 链表2的头指针
head2 = stu2;
struct Student *p, *p1;
p1 = stu1;
printf("9-11----list a:\n");
for (int i = 1; p1 < stu1 + L1; i++)
{
p = p1;
p1->next = stu1 + i;
printf("%s,%s\n", p->num, p->name);
p1 = p1->next;
}
p->next = NULL;
printf("9-11----list b:\n");
struct Student *p2;
p2 = stu2;
for (int j = 1; p2 < stu2 + L2; j++)
{
p = p2;
p2->next = stu2 + j;
printf("学号:%s,姓名:%s\n", p2->num, p2->name);
p2 = p2->next;
}
p->next = NULL;
del(head1, head2);
printf("9-11----result:\n");
print(stu1);
return SUCCESS;
}

int main()
{
chapter9_11();
}