将两个排序链表合并为一个新的排序链表
样例
给出 1->3->8->11->15->null
,2->null
, 返回1->2->3->8->11->15->null
。
思想:因为两个链表均是排好序的,因此只需要新建一个链表,将两个链表进行大小对比后,存放在新链表中即可。
注意:两个链表不同长度的处理方法。
1、非递归程序:
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/*
* @param l1: ListNode l1 is the head of the linked list
* @param l2: ListNode l2 is the head of the linked list
* @return: ListNode head of linked list
*/
ListNode * mergeTwoLists(ListNode * l1, ListNode * l2) {
// write your code here
if(l1==NULL)
return l2;//若l1为空
if(l2==NULL)
return l1;//若l2为空
ListNode *ptr=(struct ListNode*)malloc(sizeof(struct ListNode));
ptr->next=NULL; //建立头结点
//或者 ListNodeptr=new ListNode(0);//因为程序中给出了ListNode//()的构造函数
ListNode*pre=ptr;//保存头结点
while(l1!=NULL&&l2!=NULL)
{
if(l1->val<=l2->val)
{ptr->next=l1;
l1=l1->next;
}
else
{
ptr->next=l2;
l2=l2->next;
}
ptr=ptr->next;
}
if(l1==NULL)
ptr->next=l2;
if(l2==NULL)
ptr->next=l1;
return pre->next;
}
};
2、递归程序(简洁但耗时)(理解并记住)
ListNode *mergetwo(ListNode* l1, ListNode* l2) {
if (NULL == l1) return l2;
else if (NULL == l2) return l1;
if (l1->val <= l2->val) {
l1->next = mergetwo(l1->next, l2);
return l1;
}
else {
l2->next = mergetwo(l1, l2->next);
return l2;
}
}
假设有两个排序链表 1->2->3->null, 2->4->null,程序具体流程如下