将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例 1:
输入:l1 = [1,2,4], l2 = [1,3,4] 输出:[1,1,2,3,4,4]
示例 2:
输入:l1 = [], l2 = [] 输出:[]
法 1 正常遍历 连接表
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
if(l1==NULL)//l1 为空
return l2;
if(l2==NULL)//l2空
return l1;
struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode)),*t = head;
//建立头节点 建立遍历指针
while(l1&&l2){
if(l1->val < l2->val){
t->next = l1;
l1 = l1->next;
}
else{
t->next = l2;
l2 =l2->next;
}
t=t->next;//链接表
}
if(l1) t->next = l1; //l1 剩下 直接链
if(l2) t->next = l2;//l2 剩下 直接连接
return head->next;
}
法2递归解决
大事化小
出口 为空则结束
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
if(!l1)
return l2;
if(!l2)
return l1;
if(l1->val < l2->val){
l1->next = mergeTwoLists(l1->next,l2);//
return l1;
}else
{
l2->next = mergeTwoLists(l1,l2->next);
return l2;
}
}