#include <iostream>
using namespace std;
struct Node
{
int data;
Node *next;
};
class LinkList
{
public:
LinkList(int a[],int n);//尾插法在单链表中插入n个数据
~LinkList();
void PrintList();
Node * GetFirst(){return first;}
private:
Node *first;
};
LinkList::LinkList(int a[],int n)
{
first = new Node; //附设头结点
Node *rear = first;
int i;
for(i=0;i<n;i++)
{
Node *s = new Node;
s->data = a[i];
rear->next = s;
rear = s;
}
rear->next = nullptr;
}
void LinkList::PrintList()
{
Node *p=first->next;
while(p)
{
cout<<p->data<<" ";
p=p->next;
}
}
LinkList::~LinkList()
{
Node *p=first,*s;
while(p)
{
s=p;
p=p->next;
delete s;
}
}
void Merge(LinkList &A, LinkList &B, int m,int n)
{
//Todo:将A和B两个非递减有序单链表合并,结果放到A链表中
Node *p = A.GetFirst() ->next;
Node *q = B.GetFirst() ->next;
Node *s, *t, *j;
t = A.GetFirst()->next;
s = B.GetFirst()->next;
//while里的m 和n 是主函数的变量,不知道怎么访问,或者有别的方法?求指教=_=
while(p)
{
if(p->data<q->data&&p)
{
t = p;
p = p->next;
}
else
{
t->next = s;
while((q->data<=p->data)&&q)
{
s = q;
q = q->next;
}
s->next = p;
s = q;
}
}
if(q)
{
t->next = q;
}
}
int main()
{
int m,n,i,x;
cin >> m;
int a[m];
for(i=0;i<m;i++)
{
cin >> a[i];
}
LinkList la(a,m);
//Todo:用与la相同方式创建单链表lb
cin >> n;
int b[n];
for(i=0;i<n;i++)
{
cin >> b[i];
}
LinkList lb(b,n);
cout<< "Merge"<<endl;
Merge(la,lb,m,n);
la.PrintList();
return 0;
}
|