PTA:7-3 两个递增链表的差集

^两个递增链表的差集

题目

在这里插入图片描述

输入样例

5
1 3 5 7 9
3
2 3 5

输出样例

3
1 7 9

代码

#include <iostream>
#include <list>
#include <unordered_set>
using namespace std;
int main() 
{
    
    
    int n1, n2;
    cin >> n1;

    list<int> a;//①
    for (int i = 0; i < n1; i++) 
    {
    
    
        int value;
        cin >> value;
        a.push_back(value);
    }

    cin >> n2;//②
    list<int> b;
    for (int i = 0; i < n2; i++) 
    {
    
    
        int value;
       cin >> value;
        b.push_back(value);
    }

    unordered_set<int> b_set(b.begin(), b.end());//③
    list<int> result;

    for (const int& val : a) //④
    {
    
    
        if (b_set.find(val) == b_set.end()) 
        {
    
    
            result.push_back(val);
        }
    }

    cout << result.size() <<endl;//⑤

    for (auto it = result.begin(); it != result.end(); ++it) 
    {
    
    
        cout << *it;
        if (next(it) != result.end()) 
        {
    
    //⑦
            cout << " ";
        }
    }
    return 0;
}

①输入第一个链表的元素个数、元素
在这里插入图片描述
②输入第二个链表的元素个数、元素在这里插入图片描述
③用unordered_set来存储第二个列表的元素,以便快速查找

④遍历第一个列表,如果元素在第二个列表中找不到,则加入结果列表
在这里插入图片描述
⑤输出结果列表的size

⑥最后输出结果列表的元素,用空格分隔
在这里插入图片描述
注意末尾没有空格,需要加上这个判断在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/m0_74195626/article/details/132943713