PTA习题 两个有序链表序列的交集

来源:互联网 发布:淘宝哪家护肤品是正品 编辑:程序博客网 时间:2024/04/30 11:31
5-52 两个有序链表序列的交集   (20分)

已知两个非降序链表序列S1与S2,设计函数构造出S1与S2的交集新链表S3。

输入格式:

输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用-11表示序列的结尾(-11不属于这个序列)。数字用空格间隔。

输出格式:

在一行中输出两个输入序列的交集序列,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL

输入样例:

1 2 5 -12 4 5 8 10 -1

输出样例:

2 5
#include <iostream>#include <cstdio>#include <cmath>#include <queue>#include <stack>#include <map>#include <algorithm>#include <vector>#include <string>#include <cstring>#include <sstream>#define INF 100000000using namespace std;vector<int> a;vector<int> b;int main(){    int x;    a.clear();    b.clear();    while(scanf("%d",&x)==1)    {        if(x==-1) break;        a.push_back(x);    }    while(scanf("%d",&x)==1)    {        if(x==-1) break;        b.push_back(x);    }    int i=0,j=0;    vector<int> ans;    ans.clear();    while(i<a.size() && j<b.size() )    {        if(a[i]==b[j])        {            ans.push_back(a[i]);            i++;            j++;        }        else if(a[i]<b[j])        {            i++;        }        else        {            j++;        }    }    if(ans.size()==0)    {        printf("NULL\n");        return 0;    }    for(int i=0;i<ans.size();i++)    {        if(i==0) printf("%d",ans[i]);        else printf(" %d",ans[i]);    }    return 0;}


0 0
原创粉丝点击