9.11有两个链表a和b,设结点中包含学号、姓名。从a链表中删去与b链表中有相同学号的那些结点。

//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;
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值