题目要求:
我的代码实现:(将交集直接接在了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;
}
这个代码确实节省了空间,题目对非交集的元素不做要求,就全删除了。