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;
}

猜你喜欢

转载自blog.csdn.net/zl1085372438/article/details/79488794