7-1 两个有序链表序列的交集

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

输入格式:

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

输出格式:

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

输入样例:

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

输出样例:

2 5
#include <iostream>  
#include <vector>  
#include <algorithm> // 用于std::copy  
  
using namespace std;  
  
vector<int> findIntersection(const vector<int>& a, const vector<int>& b) {  
    vector<int> intersection;  
    auto it1 = a.begin(), it2 = b.begin();  
  
    while (it1 != a.end() && it2 != b.end()) {  
        if (*it1 == *it2) {  
            intersection.push_back(*it1);  
            ++it1;  
            ++it2;  
        } else if (*it1 < *it2) {  
            ++it1;  
        } else {  
            ++it2;  
        }  
    }  
  
    return intersection;  
}  
  
int main() {  
    vector<int> a, b;  
    int num;  
  
    // 读取第一个序列  
    while (cin >> num && num != -1) {  
        a.push_back(num);  
    }  
  
    // 读取第二个序列  
    while (cin >> num && num != -1) {  
        b.push_back(num);  
    }  
  
    vector<int> c = findIntersection(a, b);  
  
    if (c.empty()) {  
        cout << "NULL" << endl;  
    } else {  
        for (size_t i = 0; i < c.size(); ++i) {  
            cout << c[i];  
            if (i + 1 < c.size()) {  
                cout << " ";  
            }  
        }  
        cout << endl;  
    }  
  
    return 0;  
}

 

 

vector<int> c = findIntersection(a, b); 的用法 

 在 C++ 中,vector<int> c = findIntersection(a, b); 的用法是调用一个名为 findIntersection 的函数,该函数接受两个 vector<int> 类型的参数(这里假设为 ab),并返回一个包含 ab 交集的新 vector<int>。然后,这个返回的 vector<int> 被赋值给另一个 vector<int> 类型的变量 c

size_tsize_t是一种无符号整数类型,它只能表示非负的整数值。这意味着size_t类型的变量不会存储负数,其取值范围是从0到系统能表示的最大正整数值。主要用于表示对象的大小、数组的索引、内存分配的大小等。它是C和C++标准库中经常使用的类型,以确保能够表示任何对象的大小而不会发生溢出。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值