[c++]代码库
//***********************************
//功能:把两个单链表合并为一个单链表,要求两个表的元素交错排列,新表利用原表结点的内存空间
//日期:2017年9月27日
//作者:Ryan2019
//***********************************
#include <iostream>
using namespace std;
typedef int LElemType;
typedef struct LNode
{
LElemType data;
LNode *next;
}* LList;
void ListCreate(LList &L,int n,LElemType a[]);//创建链表
void Listshow(LList &L);//显示链表
bool ListMerge(LList &A,LList &B);//合并
int main()
{
LList A,B; int m=3,n=5;
LElemType a[3]={1,2,3};
LElemType b[5]={4,5,6,7,8};
ListCreate(A,m,a);
ListCreate(B,n,b);
cout<<"原链表A为:"; Listshow(A);
cout<<"原链表B为:"; Listshow(B);
ListMerge(A,B);
cout<<"合并后链表为:"; Listshow(A);
return 0;
}
void ListCreate(LList &L,int n,LElemType a[])
{
LList p; int i;
L=new LNode; L->next=NULL;
for(i=n-1;i>=0;i--)
{
p=new LNode;
p->data=a[i];
p->next=L->next;
L->next=p;
}
}
void Listshow(LList &L)
{
LList p;
for(p=L->next;p;p=p->next)
{
cout<<p->data<<" ";
}
cout<<endl;
}
bool ListMerge(LList &A,LList &B)
{
LList p,q,t;
p = A->next;
q = B->next;
delete B;
while (p&&q)
{
t=p;
p=p->next;
t->next=q;
t=q;
q=q->next;
t->next=p;
}
if(!p)
{
t->next=q;
}
else if(!q)
{
t->next=p;
}
return true;
}