一种合并链表方法实现 严蔚敏 数据结构
参考别人的,合并代码经过修改,个人觉得这种比较容易理解
#include<iostream>
using namespace std;
typedef int ElemType;
//两个递增的链表合并成递增的链表。
typedef struct LNode
{
ElemType data;
struct LNode *next;
}
LNode;
typedef LNode *LinkList;
void CreatList(LinkList &L,int n)
{
LinkList p,q;
L=new LNode; //////头结点为空
L->next=NULL;
q=L;
cout<<"请从小到大输入链表的元素:";
for (int i=1;i<=n;i++)
{
p=new LNode;
cin>>p->data;
q->next = p;
p->next = NULL;
q = p;
//p->next=q->next;
//q->next=p;
//q=q->next;
}
cout<<"所创建得的递增有序链表为:";
p=L->next;
for (int j=1;j<=n;j++)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
void CreatC(LinkList &A,LinkList &B,LinkList &C,int n)
{
LinkList pa,pb,pre=NULL/*C结点的上一个结点*/,q/*t*/;
pa=A->next;
pb=B->next;
free(A);
C = B;
C->next = NULL;
while (pa&&pb)
{
if (pa->data<=pb->data)
{
q = pa;
pa = pa->next;
}
else
{
q = pb;
pb = pb->next;
}
q->next = C->next;
C->next = q;
}
while (pa)
{
q = pa; pa= pa->next;
q->next = C->next;
C->next = q;
}
while (pb)
{
q = pb; pb = pb->next;
q->next = C->next;
C->next = q;
}
cout<<"合并后的递减有序链表为:";
pa=C;
for (int j=1;j<=n;j++)
{
cout<<pa->next->data<<" ";
pa=pa->next;
}
cout<<endl;
// getchar();
}
void main()
{
LinkList A,B,C;
int n,m,k;
cout<<"请输入链表***A***的长度:";
cin>>n;
CreatList(A,n);
cout<<"请输入链表***B***的长度:";
cin>>m;
CreatList(B,m);
k=m+n;
CreatC(A,B,C,k);
}