1. 程式人生 > >5-16 兩個有序連結串列序列的交集 (20分)

5-16 兩個有序連結串列序列的交集 (20分)

已知兩個非降序連結串列序列S1與S2,設計函式構造出S1與S2的交集新連結串列S3。
輸入格式:

輸入分兩行,分別在每行給出由若干個正整數構成的非降序序列,用-1−1表示序列的結尾(-1−1不屬於這個序列)。數字用空格間隔。
輸出格式:

在一行中輸出兩個輸入序列的交集序列,數字間用空格分開,結尾不能有多餘空格;若新連結串列為空,輸出NULL。
輸入樣例:

1 2 5 -1
2 4 5 8 10 -1
輸出樣例:

2 5

#include<stdio.h>
#include<stdlib.h>
typedef struct Node* List;
struct Node{
    int Data
; struct Node*Next; }; List Search(List L1,List L2,List L3); List init(); void Insert(List L,int t); int main(){ List L1,L2,L3; int t; L1=init(); L2=init(); L3=init(); while(1){ scanf("%d",&t); if(t==-1){ break; } else{ Insert(L1,t); } } while
(1){ scanf("%d",&t); if(t==-1){ break; } else{ Insert(L2,t); } } // for(;L1!=NULL;L1=L1->Next){ // printf("%d ",L1->Data); // } if((!L1)||(!L1->Next)||(!L2)||(!L2->Next)){ printf("NULL"); return
0; } L3=Search(L1,L2,L3); if((!L3)||(!L3->Next)){ printf("NULL"); return 0; } for(L3=L3->Next;L3->Next!=NULL;L3=L3->Next){ printf("%d ",L3->Data); } printf("%d",L3->Data); return 0; } List init(){ List L; L=(List)malloc(sizeof(struct Node)); if(!L)return NULL; L->Next=NULL; return L; } void Insert(List L,int t){ List p=(List)malloc(sizeof(struct Node)); if(!p)return ; p->Data=t; p->Next=L->Next; L->Next=p; return ; } List Search(List L1,List L2,List L3){ List p,q; p=L1->Next; q=L2->Next; while((p!=NULL)&&(q!=NULL)){ if(p->Data<q->Data){ q=q->Next; } else if(p->Data>q->Data){ p=p->Next; } else{ Insert(L3,p->Data); p=p->Next; q=q->Next; } } return L3; }