已知两个非降序链表序列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>
typedef struct s{
int data;
struct s *next;
}node,*snode;
node *creatlist(void);
node *intersection(node *a,node *b);
void print(node *head);
int main(){
snode L1,L2; //L1和L2都是指针;
L1=creatlist();
print(L1);
printf("\n");
L2=creatlist();
print(L2);
printf("\n");
print(intersection(L1,L2));
}
node *creatlist(void){ //创建链表
node *head=NULL;
node *p=NULL;
node *r=NULL;
int x;
scanf("%d",&x);
while(x!=-1){
p=(node *)malloc(sizeof(struct s));
p->data=x;
p->next=NULL;
if(head==NULL){
head=p;
r=p;
}else{
r->next=p;
r=p;
}
scanf("%d",&x);
}
return head;
}
node *intersection(node *a,node *b) { //寻找两个有序链表的交集
node *r;
node *c=NULL;
node *head=NULL;
while(a!=NULL&&b!=NULL){
if(a->data<b->data){
a=a->next;
}else if(a->data>b->data){
b=b->next;
}else if(a->data==b->data){
r=(node *)malloc(sizeof(struct s));
r->data=a->data;
r->next=NULL;
if(head==NULL){
head=r;
c=r;
}else{
c->next=r;
c=r;
}
a=a->next;
b=b->next;
}
}
return head;
}
void print(node *head){ //打印一个列表
node *p;
p=head;
while(p){
printf("%d->",p->data);
p=p->next;
}
if(p==NULL)
printf("NULL");
}