描述
巳知线性表LA和线性表LB中的数据元素按值非递减有序排列,现要求将LA和LB归并为一个新的线性表LC,且LC中的元素仍按值非递减有序排列。
输入
三行,第一行A,B集合的个数n,m
第二行:集合A的数据;
第三行:集合B的数据。
输出
二行,第一行,集合C的个数k
第二行:集合C的数据。
//用链表怎么进行怎么进行集合合并,一直没有思路,看了用链表进行多项式的合并,改了一下,有问题的地方请大佬们指正
#include<iostream>
using namespace std;
struct Node
{
int data;
Node *next;
};
class list
{
Node *first;
public:
list(int n);
//~list();
void print();
void add(list &a,list &b);
};
list::list(int n)
{
first=new Node;
Node *s=NULL,*r=r=first;
for(int i=1;i<=n;i++)
{
s=new Node;
cin>>s->data;
r->next=s;
r=s;
}
r->next=NULL;
}
void list::add(list &a,list &b)
{
Node *pa,*pb,*p,*pc;
pa=a.first;
pa=pa->next;
pb=b.first;
pb=pb->next;
pc=a.first;
p=b.first;
delete p;
while(pa->next!=NULL&&pb->next!=NULL)
{
if(pa->data<pb->data)
{
pc->next=pa;
pc=pa;
pa=pa->next;
continue;
}
if(pa->data>pb->data)
{
pc->next=pb;
pc=pb;
pb=pb->next;
continue;
}
if(pa->data==pb->data)
{
pc->next=pa;
pc=pc->next;
pa=pa->next;
p=pb;
pb=pb->next;
delete p;
continue;
}
}
pc=pc->next;
if(pa->next==NULL)
pc->next=pb;
if(pb->next==NULL)
pc->next=pa;
}
void list::print()
{
Node *p=first->next,*q=first->next;
int n=0;
while(p)
{
//cout<<p->data<<" ";
n++;
p=p->next;
}
cout<<n;
cout<<endl;
while(q)
{
cout<<q->data<<" ";
q=q->next;
}
cout<<endl;
}
/*list::~list()
{
Node *p=first,*q;
while(p)
{
q=p->next;
delete p;
p=q;
}
}*/
int main()
{
int n,m;
cin>>n>>m;
list a(n);
//a.print();
list b(m);
//b.print();
a.add(a,b);
a.print();
return 0;
}