王道数据结构第42页15题

题目要求:
在这里插入图片描述
我的代码实现:(将交集直接接在了A链表的屁股后面)

#include<stdio.h>
#include<stdlib.h>

#define ElemType int
typedef struct LNode{
	ElemType data;
	struct LNode* next;
}LNode,*LinkList;

LinkList List_TailInsert(LinkList &L)
{
   int x;
   L=(LinkList)malloc(sizeof(LNode));
   L->next=NULL;
   LNode *s,*p=L;
   scanf("%d",&x);
   while(x!=9999)
   {
   	   s=(LNode*)malloc(sizeof(LNode));
   	   s->data=x;
   	   s->next=p->next;
   	   p->next=s;
   	   p=s;
   	   scanf("%d",&x);
   }
   return L;
}

void CommenSet(LinkList &L1,LinkList &L2)
{
	LNode *r=L1;
	for(r;r->next!=NULL;r=r->next);
	
	LNode *p=L1->next,*q=L2->next;
	while(p&&q)
	{
	   if(p->data>q->data)q=q->next;
	   else if(p->data<q->data)p=p->next;
	   else if(p->data==q->data)
	   {
	   	  r->next=(LNode*)malloc(sizeof(LNode));
	   	  r->next->data=p->data;
	   	  r->next->next=NULL;
	   	  r=r->next;
	   	  p=p->next;q=q->next;
	   }
	}
}

void ShowList(LinkList L)
{
	LNode *p=L->next;
	while(p)
	{
		printf("%d ",p->data);
		p=p->next;
	}
	printf("\n");
}

int main()
{
	LinkList A,B;
	
	printf("构造递增A链表:\n");
	A=List_TailInsert(A);
	printf("构造递增B链表:\n");
	B=List_TailInsert(B);
	
	CommenSet(A,B);
	
	printf("输出处理之后的A链表:\n");
	ShowList(A);
	
	return 0;
}

参考王道视频讲解的代码实现:

#include<stdio.h>
#include<stdlib.h>

#define ElemType int
typedef struct LNode{
	ElemType data;
	struct LNode* next;
}LNode,*LinkList;

LinkList List_TailInsert(LinkList &L)
{
   int x;
   L=(LinkList)malloc(sizeof(LNode));
   L->next=NULL;
   LNode *s,*p=L;
   scanf("%d",&x);
   while(x!=9999)
   {
   	   s=(LNode*)malloc(sizeof(LNode));
   	   s->data=x;
   	   s->next=p->next;
   	   p->next=s;
   	   p=s;
   	   scanf("%d",&x);
   }
   return L;
}

LinkList Union(LinkList &L1,LinkList &L2)
{
	LNode *pa=L1->next,*pb=L2->next,*pc=L1;
	while(pa&&pb)
	{
		if(pa->data==pb->data)
		{
			pc->next=pa;
			pc=pa;
			LNode *u=pb;
			pb=pb->next;
			free(u);
		}
		else if(pa->data<pb->data)
		{
			LNode *u=pa;
			pa=pa->next;
			free(u);
		}
		else
		{
			LNode *u=pb;
			pb=pb->next;
			free(u);
		}
	}
	
	while(pa)
	{
		LNode *u=pa;
		pa=pa->next;
		free(u);
	}
	while(pb)
	{
		LNode *u=pb;
		pb=pb->next;
		free(u);
	}
	
	pc->next=NULL;
	free(L2);
	return L1;
}

void ShowList(LinkList L)
{
	LNode *p=L->next;
	while(p)
	{
		printf("%d ",p->data);
		p=p->next;
	}
	printf("\n");
}

int main()
{
	LinkList A,B;
	
	printf("构造递增A链表:\n");
	A=List_TailInsert(A);
	printf("构造递增B链表:\n");
	B=List_TailInsert(B);
	
	A=Union(A,B);
	
	printf("输出处理之后的A链表:\n");
	ShowList(A);
	
	return 0;
}

这个代码确实节省了空间,题目对非交集的元素不做要求,就全删除了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值