//C程序设计第四版(谭浩强)
//章节:第九章 用户自己建立数据类型
//题号:9.11
//题目:有两个链表a和b,设结点中包含学号、姓名。从a链表中删去与b链表中有相同学号的那些结点。
#include <stdio.h>
#include <stdlib.h>
#define LEN sizeof(struct student)
struct student
{
long num;
char name[10];
struct student *next;
};
struct student *create()
{
struct student *head=NULL,*p1,*p2;
int n=0;
p1=p2=(struct student *)malloc(LEN);
printf("input num,name(if num=0 stop):\n");
scanf("%ld %s",&p1->num,p1->name);
while(p1->num!=0)
{
n=n+1;
if(n==1)
head=p1;
else
p2->next=p1;
p2=p1;
p1=(struct student *)malloc(LEN);
scanf("%ld %s",&p1->num,p1->name);
}
p2->next=NULL;
return head;
}
struct student *search(struct student *head,int x)
{
struct student *p=head;
while(p!=NULL)
{
if(p->num==x)
return p;
p=p->next;
}
return NULL;
}
struct student *del(struct student *head,int x)
{
struct student *p1,*p2;
if(head==NULL)
{
printf("list is null!\n");
return NULL;
}
p1=head;
while(p1->num!=x&&p1->next!=NULL)
{
p2=p1;
p1=p1->next;
}
if(p1->num==x)
{
if(head==p1)
head=p1->next;
else
p2->next=p1->next;
printf("the student whose num is %ld is deleted.\n",p1->num);
free(p1);
}
else
printf("num %ld is not found!\n",x);
return head;
}
void print(struct student *head)
{
struct student *p;
p=head;
printf("output list:\n");
while(p!=NULL)
{
printf("%ld\t%s\n",p->num,p->name);
p=p->next;
}
}
int main()
{
struct student *head_a,*head_b,*p1,*p2;
int x;
printf("input list a:\n");
head_a=create();
printf("input list b:\n");
head_b=create();
p1=head_b;
while(p1!=NULL)
{
x=p1->num;
while((p2=search(head_a,x))!=NULL)
{
head_a=del(head_a,x);
}
p1=p1->next;
}
print(head_a);
return 0;
}
9.11有两个链表a和b,设结点中包含学号、姓名。从a链表中删去与b链表中有相同学号的那些结点。
最新推荐文章于 2021-12-31 13:00:42 发布