好不容易写出来了,试了几次没有什么问题,大家发现什么问题请指正。谢谢!
#include<stdio.h>
#include<stdlib.h>
#define LEN sizeof(struct student)
struct student{
long num;
char name[20];
struct student *NEXT;
};
int main()
{
struct student *creat();
struct student *delete(struct student *,struct student *);
void print(struct student *);
struct student *head1,*head2;
printf("建立第一个表\n");
head1=creat();
printf("建立第二个表\n");
head2=creat();
print(delete(head1,head2));
return 0;
}
struct student *creat()
{
struct student *head,*p1,*p2;
int n=0;
do{
n++;
if(n==1){
head=p1=p2=malloc(LEN);
scanf("%ld %20s",&p1->num,&p1->name);
}else{
p2->NEXT=p1;
p2=p1;
}
p1=malloc(LEN);
scanf("%ld %20s",&p1->num,&p1->name);
}while(p1->num!=0);
p2->NEXT=NULL;
return head;
}
struct student *delete(struct student *p1,struct student *p2)
{
struct student *head1,*head2,*p3;
head2=p2;
for(head1=p3=p1;p1!=NULL;p1=p1->NEXT){
for(p2=head2;p2!=NULL;p2=p2->NEXT){
if(p1->num==p2->num){
if(p1==head1){//如果是第一位,就后移
head1=head1->NEXT;
}else{//正常情况删除相同学号的结点
p3->NEXT=p1->NEXT;
p1=p3;//删除后p1后移一位
}
}
}
p3=p1;/*在p1=p1->NEXT前让p3=p1,使p1指向删除项,
p3指向前一项,这样删除操作能正常进行*/
}
return head1;
}
void print(struct student *p)
{
do{
printf("%ld %s\n",p->num,p->name);
p=p->NEXT;
}while(p!=NULL);
}