题目
设带头结点的线性单链表A=(a1,a1......,am),B=(b1,b2,......,bn)。试编写算法按下列规则合并A、B为线性单链表C,使得:
c=(a1,b1,....am.bm,bn+1,.....bn),m<n
c=(b1,a1,.....bn,an,am+1,.......am),m>=n
该题目以我个人的思考来说对于链表之间的题目,此类型题目还算简单就是要注意一些小细节,例如在使用结点之前需要保存它的后一个结点否则后面的数据便会消失。
根据题目可以看出如果a链表比b链表长则b的数据在新链表的第一个位置,且a链表穿插存储在新链表之中,最后将a所剩余的链表存储在新链表的最后,若b链表比a链表长则是一样的道理,在这里就不多说了,创建和输出链表大家应该已经很熟悉了,所以我就直接上代码啦!
该题的解题代码如下所示:
#include<iostream>
#include<stdlib.h>
using namespace std;
int Len1=0,Len2=0; //保存a,b链表的长度
struct st{
int n;
struct st *next;
};
struct st *create2();
struct st *create1();
void print(struct st *phead);
struct st *he(struct st *s1,struct st *s2);
struct st *create1()
{
struct st *phead,*s,*r;
int x;
phead=(struct st*)malloc(sizeof(struct st));
phead->next=NULL;
s=(struct st*)malloc(sizeof(struct st));
r=phead;
cout<<"当输入数据为0时自动退出!"<<endl;
cin>>s->n;
Len1=1;
while(s->n!=0)
{
r->next=s;
s->next=NULL;
r=s;
s=(struct st*)malloc(sizeof(struct st));
cin>>s->n;
Len1++;
}
free(s);
return phead;
}
struct st *create2()
{
struct st *phead,*s,*r;
int x;
phead=(struct st*)malloc(sizeof(struct st));
phead->next=NULL;
s=(struct st*)malloc(sizeof(struct st));
r=phead;
cout<<"当输入数据为0时自动退出!"<<endl;
cin>>s->n;
Len2=1;
while(s->n!=0)
{
r->next=s;
s->next=NULL;
r=s;
s=(struct st*)malloc(sizeof(struct st));
cin>>s->n;
Len2++;
}
free(s);
return phead;
}
void print(struct st *p) //与普通链表打印函数一样
{
struct st *ptemp;
ptemp=(struct st*)malloc(sizeof(struct st));
ptemp=p->next;
while(ptemp!=NULL)
{
cout<<ptemp->n<<"\t";
ptemp=ptemp->next;
}
cout<<endl;
}
struct st *he(struct st *s1,struct st *s2) //求和
{
if(s1==NULL||s2==NULL) return s1?s1:s2; //如果s1或s2其中一个为空时则返回不为空的呢个链表即可
struct st *head=(struct st*)malloc(sizeof(struct st));
struct st *tail,*p1,*p2; //tail为一个新结构体指针,指向head的尾部方便插入
p1=s1->next;
p2=s2->next;
tail=head; //将head作为头结点返回
if(Len1>=Len2) //如果a链表的长度大于b链表的长度则运行
{
while(p2) //将b链表的内容运行结束
{
tail->next=p2; //将数据穿插着写入head链表之中
p2=p2->next;
tail=tail->next;
tail->next=p1;
p1=p1->next;
tail=tail->next;
}
tail->next=p1; //结束后直接链接a链表未运行完的数据存进tail也就是head链表之中即可
}
else
{
while(p1) //与a链表比b链表长是一个道理
{
tail->next=p1;
p1=p1->next;
tail=tail->next;
tail->next=p2;
p2=p2->next;
tail=tail->next;
}
tail->next=p2;
}
return head; //返回新的链表即为合并后的链表
}
int main()
{
struct st *s1,*s2,*C;
s1=create1();
cout<<"s1:"<<endl;
print(s1);
s2=create2();
cout<<"s2:"<<endl;
print(s2);
C=he(s1,s2);
cout<<"合并之后的链表:"<<endl;
print(C);
return 0;
}
该题目的重点的代码在he函数哪里,就是将其先判断链表长度大小然后再根据长度大小进行交替插入的形式保存在新链表之中,运行改代码之后的结果如下图所示:
该题就讲解到这里,大家如果有需要数据结构的题目或一些讲解可以关注我的这一系列专栏!