1.建立三个链表
2.定义三个链表指针*t、*p、*q
3.*p、*q分别指向两个链表的next结点;*t指向一个链表的头结点,这个头结点就成为新链表的头结点
4.选择下一个结点,根据一定的判定条件,如果下一个结点为p的结点,(1)先让t指向p,(2)t向后移动既t=t->next,(3)p的指向后移既p=p->next。
5.判断是否有一个链表合并完,如果q,p有一个为空即为有一个链表合并完,这样只需处理另一个结点全部连接到新链表中即可。如果p为空,执行t->next=q;break;
注:一定不能忽略break;
6.返回新链表的头结点.
#include <iostream>
#include<stdlib.h>
using namespace std;
struct node
{
int x;
struct node *next;
};
//顺序建表
struct node *creatListShun(int lenth)
{
struct node *head,*t,*p;
int i;
head=(struct node *)malloc(sizeof(struct node));
head->next=NULL;
t=head;
for(i=0; i<lenth; i++)
{
p=(struct node *)malloc(sizeof(struct node));
p->x=i;
p->next=NULL;
t->next=p;
t=p;
}
return head;
}
//链表合并
struct node *hebing(struct node *head1,struct node *head2)
{
struct node *t,*p,*q;
t=head1;
p=head1->next;
q=head2->next;
while(t)
{
if(p->x<q->x)
{
t->next=p;
p=p->next;
t=t->next;
}
else
{
t->next=q;
q=q->next;
t=t->next;
}
if(p==NULL)
{
t->next=q;
break;
}
if(q==NULL)
{
t->next=p;
break;
}
}
return head1;
}
int main()
{
struct node *head1,*t1;
head1=creatListShun(10);//顺序建链表
t1=head1->next;
cout<<"顺序建链表1 :";
while(t1!=NULL)
{
cout<<t1->x<<" ";
t1=t1->next;
}
cout<<endl;
struct node *head2,*t2;//逆序建链表
head2=creatListShun(10);
t2=head2->next;
cout<<"顺序建链表2 :";
while(t2!=NULL)
{
cout<<t2->x<<" ";
t2=t2->next;
}
cout<<endl;
//链表合并
head1=hebing(head1,head2);
t1=head1->next;
cout<<"链表合并 :";
while(t1!=NULL)
{
cout<<t1->x<<" ";
t1=t1->next;
}
cout<<endl;
return 0;
}