集合合并(oj)

已知集合A与集合B,且第个集合内数据是唯一的。求A,B集合合并成新的集合C,要求C集合内的数据也是唯一的。并指出C集合的个数。

输入
三行,第一行分别为集合A,B的个数
第二行为A集合的数据
第三行为B集合的数据
输出
两行
第一行集合C的个数
第二行为C集合的数据
样例输入
4 5
12 34 56 78
34 67 89 34 76
样例输出
7
12 34 56 78 67 89 76

解题思想:
已知集合A,B,求集合C(集合中不存在相同的元素),先用单链表储存集合A,然后在将集合B中不同于A集合中的元素插入到其中即可;

#include <iostream>
#define max 105
using namespace std;
struct node{
    int data;
    node *next;
};
class line{
    node *first;
public:
    line();
    line(int c[],int n);
    void inset(int x);
    int get_l();
    void println();
};
line::line(){
    first=new node;
    first->next=nullptr;
}
line::line(int c[],int n){
        first=new node;
        node *r=first,*s=nullptr;
        for(int i=0;i<n;i++)
            {
                s=new node;
                s->data=c[i];
                r->next=s;
                r=s;
            }
        r->next=nullptr;
}
void line::inset(int x){
    node *p=first->next;
    while(p->data!=x&&p->next!=nullptr){
          p=p->next;
    }
    if(p->next==nullptr){
        node *s=nullptr;
        s=new node;
        s->data=x;
        s->next=p->next;
        p->next=s;
    }

}
void line::println()
{
    node *p=first->next;
    while(p!=nullptr)
        {
            cout<<p->data<<" ";
            p=p->next;
        }
    cout<<endl;
}
int line::get_l(){
    node *p=first->next;
    int l=0;
    while(p!=nullptr)
        {
            l++;
            p=p->next;
        }
    return l;
}
int main()
{
    int a1,b1,a[max],b[max];
    cin>>a1>>b1;
    int a2,b2;
	int i;
    for(i=0;i<a1;i++){
        cin>>a2;
        a[i]=a2;
    }
     for(i=0;i<b1;i++){
        cin>>b2;
        b[i]=b2;
    }
    line one{a,a1};
    for(i=0;i<b1;i++)
        one.inset(b[i]);
    cout<<one.get_l()<<endl;
    one.println();
    return 0;
}

性质:属于单链表的构成,以及插入数据,和输出数据的运用;

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值