PTA 兩個有序鏈表序列的交集 水題

7-52 兩個有序鏈表序列的交集(20 分)

已知兩個非降序鏈表序列S1與S2,設計函數構造出S1與S2的交集新鏈表S3。

輸入格式:

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

輸出格式:

在一行中輸出兩個輸入序列的交集序列,數字間用空格分開,結尾不能有多餘空格;若新鏈表爲空,輸出NULL

輸入樣例:

1 2 5 -1
2 4 5 8 10 -1

輸出樣例:

2 5

水題。

O(n)複雜度

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
#include <vector>
#include <sstream>
#include <map>
#include <queue>
#include <stack>
#include <cstring>
#include <set>
#include <cmath>
#define INF 1000000

using namespace std;
int a[1000005];
int b[1000005];
int ans[2000005];
int lena;
int lenb;


int main()
{
    int i=0;
    int x=0;
    while(1)
    {
        scanf("%d",&x);
        if(x==-1) break;
        a[i++]=x;
    }
    lena=i;
    i=0;
    while(1)
    {
        scanf("%d",&x);
        if(x==-1) break;
        b[i++]=x;
    }
    lenb=i;
    int j=0;
    i=0;
    int k=0;
    if(lena==0 && lenb==0)
    {
        printf("NULL\n");
        return 0;
    }

    while(i<lena && j<lenb)
    {
        if(a[i]<b[j])
        {
            i++;
        }
        else if(a[i]>b[j])
        {
            j++;
        }
        else
        {
            ans[k++]=a[i];
            i++;
            j++;
        }
    }
    if(k==0)
    {
        printf("NULL\n");
        return 0;
    }
    for(int i=0;i<k;i++)
    {
        if(i==0) printf("%d",ans[i]);
        else printf(" %d",ans[i]);
    }
    printf("\n");


    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章