数据结构与算法题目集 7-52 两个有序链表序列的交集

7-52 两个有序链表序列的交集 (20分)

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

输入格式:

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

输出格式:

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

输入样例:

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

输出样例:

2 5

题解: 

链表写到猴年马月,所以我永远喜欢STL!!!(震声)

#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
vector<int> a, b, ans;

inline const int read()
{
    int x = 0, f = 1; char ch = getchar();
    while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); }
    while (ch >= '0' && ch <= '9') { x = (x << 3) + (x << 1) + ch - '0'; ch = getchar(); }
    return x * f;
}

int main()
{
    int n;
    while (~(n = read())) a.push_back(n);
    while (~(n = read())) b.push_back(n);
    set_intersection(a.begin(), a.end(), b.begin(), b.end(), back_inserter(ans));
    bool flag = false;
    for (auto it : ans)
    {
        printf("%s%d", flag ? " " : "", it);
        flag = true;
    }
    if (ans.empty()) printf("NULL");
    return 0;
}
发布了367 篇原创文章 · 获赞 148 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_35850147/article/details/103572714