非递减有序集合合并(线性表)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_43244265/article/details/102760383

巳知线性表LA和线性表LB中的数据元素按值非递减有序排列,现要求将LA和LB归并为一个新的线性表LC,且LC中的元素仍按值非递减有序排列。

输入
三行,第一行A,B集合的个数n,m
第二行:集合A的数据;
第三行:集合B的数据。
输出
二行,第一行,集合C的个数k
第二行:集合C的数据。
样例输入
11 12
2 4 6 7 8 9 12 34 56 78 89
3 5 7 9 12 34 56 98 234 456 789 1234
样例输出
18
2 3 4 5 6 7 8 9 12 34 56 78 89 98 234 456 789 1234
提示
n,m<255

AC代码:

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=10000;
template<class T>
struct node
{
   int data;
   //node<T> *r;
    node<T>* next;
};
template<class T>
class lian
{
   node<T> *first;
   node<T> *r;
   public:
   lian();
   lian(T a[],int n);
   void cha(int a);
   void show();
   //void zhishan(T n);
   //void weishan(int n);
};
template <class T>
lian<T>::lian()
{
    first=new node<T>;
    first->next=NULL;
}
template <class T>
lian<T>::lian(T a[],int n)
{
    first=new node<T>;
    //node<T> *r=first;
    r=first;
     node<T> *s=NULL;
    for(int i=0;i<n;i++)
    {
        s=new node<T>;
        s->data=a[i];
        r->next=s;
        r=s;
    }
    r->next=NULL;
}
template <class T>
void lian<T>::cha(int a)
{
    node<T> *s;
    s=new node<T>;
    s->data=a;
     node<T> *p;
    p=first;
    while(p->next!=NULL)
    {
        if(p->next->data==a)return;
       if(p->next->data>a)
        break;
        p=p->next;
    }
    if(p->next!=NULL)
    {
        s->next=p->next;
        p->next=s;
    }
    else
    {
       p->next=s;
       r=s;
    r->next=NULL;
    }
}
template <class T>
void lian<T>::show()
{
    node<T> *p;
    p=first->next;
    int t=0,h[maxn];
    while(p!=NULL)
    {
        h[t]=p->data;
        p=p->next;
        t++;
    }
    cout<<t<<endl;
    for(int i=0;i<t;i++)
    {
        cout<<h[i]<<" ";
    }
    cout<<endl;
}
int main()
{
   int a[maxn],b[maxn];
   int x,y;
   cin>>x>>y;
   for(int i=0;i<x;i++)
   {
       cin>>a[i];
   }
   for(int i=0;i<y;i++)
   {
       cin>>b[i];
   }
   lian<int> k(a,x);
 for(int i=0;i<y;i++)
 {
     k.cha(b[i]);
 }
   k.show();

}

猜你喜欢

转载自blog.csdn.net/weixin_43244265/article/details/102760383