已知兩個非降序鏈表序列S1與S2,設計函數構造出S1與S2的交集新鏈表S3。
輸入格式:
輸入分兩行,分別在每行給出由若干個正整數構成的非降序序列,用−表示序列的結尾(−不屬於這個序列)。數字用空格間隔。
輸出格式:
在一行中輸出兩個輸入序列的交集序列,數字間用空格分開,結尾不能有多余空格;若新鏈表為空,輸出NULL
。
輸入樣例:
1 2 5 -1
2 4 5 8 10 -1
輸出樣例:
2 5
#include<iostream> using namespace std; typedef struct LNode { int data; struct LNode *next; }LNode,*List; void creat(List &l1)//傳入一個指向鏈表結點的指針,以這個指針為頭結點,構建鏈表 {//注意:這里必須傳入引用,因為會改變l1指向的值,一開始傳入的是一個空指針,后來指向了構造的結點,改變了l1的值,所以要用reference List p,temp; p = (LNode*)malloc(sizeof(LNode)); l1 = p; int e; while(scanf("%d",&e)!=EOF) { if(e == -1) return; temp = (LNode*)malloc(sizeof(LNode)); temp ->data = e; temp ->next = NULL; p->next = temp; p = p->next; } } List mergeTOInter(List l1,List l2) { List l;//l指向表頭 l = (List)malloc(sizeof(LNode));//先構造頭節點 List p = l; l->next = NULL; l1 = l1->next;//l1 and l2 都有頭節點 l2 = l2->next; while(l1!=NULL&&l2!=NULL)//l1 and l2 不為空,找到它們中相同的元素的結點,使p指向這個結點, {// if(l1->data < l2->data) l1 = l1->next; else if(l1->data > l2->data) l2 = l2->next; else { p->next = l1; l1 = l1->next; l2 = l2->next; p = p->next; } } return l;// } void countlist(List l) {//打印鏈表的data List p = l; p = p->next; if(p==NULL) { printf("NULL"); return; } while(p) { if(p->next != NULL) printf("%d ",p->data); else printf("%d",p->data); p = p->next; } } int main() { List l1, l2, l; creat(l1); creat(l2); l = mergeTOInter(l1,l2); countlist(l); return 0; }