7-171 两个有序链表序列的交集 (60 分)
已知两个非降序链表序列S1与S2,设计函数构造出S1与S2的交集新链表S3。
输入格式:
输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用−1表示序列的结尾(−1不属于这个序列)。数字用空格间隔。
输出格式:
在一行中输出两个输入序列的交集序列,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL。
输入样例:
1 2 5 -1
2 4 5 8 10 -1
输出样例:
2 5
方法一:数组实现:
#include<stdio.h>
int b[10000000],a[10000000],c[10000000];
int main()
{
int k,i=0,j=0,q=0;
while(1)
{
scanf("%d",&a[i]);
if(a[i]==-1)break;
i++;
}
while(1)
{
scanf("%d",&b[j]);
if(b[j]==-1)break;
j++;
}
int p1=0,p2=0;
while(p1<i&&p2<j)
{
if(a[p1]==b[p2])
{
c[q++]=a[p1];
p1++;
p2++;
}else if(a[p1]<b[p2])
{
p1++;
}else
{
p2++;
}
}
if(q){
for(i=0;i<q-1;i++)
printf("%d ",c[i]);
printf("%d",c[i]);}
else
printf("NULL");
}
方法二:链表实现:
#include<stdio.h>
#include<stdlib.h>
typedef struct list{
int data;
struct list *next;
}list;
void set(list *head)
{
if(head==NULL)
{
printf("NULL");
}else
while(head)
{
printf("%d",head->data);
head=head->next;
if(head)
printf(" ");
}
}
list *Greatlist()
{
list *t,*p,*head=NULL;
int n;
while(1)
{
scanf("%d",&n);
if(n==-1)
break;
t=(list*)malloc(sizeof(struct list));
t->data=n;
t->next=NULL;
if(head==NULL)
head=t;
else
{
p->next=t;
}
p=t;
}return head;
}
void hed(list *s1,list *s2)
{
list *s3=NULL,*t,*p;
while(s1&&s2){
if(s1->data==s2->data)
{
t=(list *)malloc(sizeof(struct list));
t->data=s1->data;
t->next=NULL;
if(s3==NULL)
s3=t;
else
p->next=t;
p=t;
s1=s1->next;
s2=s2->next;
}else if(s1->data<s2->data)
{
s1=s1->next;
}
else{
s2=s2->next;}
}
set(s3);
}
int main()
{
list *s1=Greatlist();
list *s2=Greatlist();
hed(s1,s2);
}