思路一:非递归
两个链表是排序过的,所以我们只需要同时遍历两个链表,比较链表元素的大小,将小的连接到新的链
表中即可。最后,可能有一个链表会先遍历完,此时,我们直接将另一个链表连接到新链表的最后即可。
struct listnode* merge_list(struct listnode* H1,struct listnode* H2)
{
struct listnode* H;
if(H1==NULL)
return H2;
if(H2==NULL)
return H1;
if((H=(struct listnode*)malloc(sizeof(struct listnode)))==NULL)
{
printf("malloc filed\n");
return NULL;
}
struct listnode* pre=H;
while(H1 && H2)
{
if(H1->data <= H2->data)
{
pre->next=H1->data;
H1=H1->next;
}else{
pre->next=H2->data;
H2=H2->next;
}
pre=pre->next;
}
pre->next=(NULL == H1 ? H2:H1);
return H->next;
}思路二:递归
在两表都不为空的情况下,如果一个表当前data更小,把该表的next修改为(next)与(另一个表)中更小者。
struct listnode* merge_list(struct listnode* H1,struct listnode* H2)
{
if(H1==NULL)
return H2;
if(H2==NULL)
return H1;
if(H1->data < H2->data){
H1-next=merge_list(H1->next,H2);
return H1;
}else{
H2-next=merge_list(H1,H2-next);
return H2;
}
}


京公网安备 11010502036488号