已知两个非降序链表序列S1与S2,设计函数构造出S1与S2的交集新链表S3。
输入格式:
输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用−1表示序列的结尾(−1不属于这个序列)。数字用空格间隔。
输出格式:
在一行中输出两个输入序列的交集序列,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL
。
输入样例:
1 2 5 -1
2 4 5 8 10 -1
输出样例:
2 5
此题核心算法借鉴一个大佬的 。
在此演示链表做法
#include<stdio.h>
#include<stdlib.h>
struct st{
int da;
struct st *next;
};
struct st *creat() //建链表 用的尾插法
{
struct st *head=NULL,*ne=NULL,*tail=NULL;
int n;
while(1)
{
scanf("%d",&n);
if(n==-1)
break;
ne=(struct st *)malloc(sizeof(struct st));
ne->da=n;
if(head==NULL)
head=ne;
else
tail->next=ne;
tail=ne;
tail->next=NULL;
}
return head;
}
struct st *cx(struct st *head1,struct st *head2) //找交集
{
struct st *ptr=NULL,*ptr1=NULL,*ptr2=NULL,*head=NULL,*tail=NULL;
ptr1=head1;
ptr2=head2;
while(ptr1!=NULL&&ptr2!=NULL)
{
if(ptr1->da<ptr2->da) //第一个链表角标后移
ptr1=ptr1->next;
else if(ptr1->da>ptr2->da) //第二个链表角标后移
ptr2=ptr2->next;
else
{
ptr=(struct st *)malloc(sizeof(struct st));
ptr->da=ptr1->da;
if(head==NULL)
head=ptr;
else
tail->next=ptr;
tail=ptr;
tail->next=NULL;
ptr1=ptr1->next;
ptr2=ptr2->next;
}
}
return head;
}
int main()
{
struct st *head1=NULL,*head2=NULL,*ptr=NULL,*head=NULL;
head1=creat();
head2=creat();
head=cx(head1,head2);
if(head==NULL)
printf("NULL");
else
{
for(ptr=head;ptr!=NULL;ptr=ptr->next)
{
printf("%d",ptr->da);
if(ptr->next!=NULL)
printf(" ");
}
}
}