思路
利用尾插法每次插入较小的结点
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
输入:l1 = [], l2 = []
输出:[]
输入:l1 = [], l2 = [0]
输出:[0]
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2){
if(list1==NULL)
return list2;
if(list2==NULL)
return list1;
//将头指向较小的结点
struct ListNode* head=NULL;
if(list1->val<list2->val){
head=list1;
list1=list1->next;
}else{
head=list2;
list2=list2->next;
}
//尾插法
struct ListNode* tail=head;
while(list1&&list2){
if(list1->val<list2->val){
tail->next=list1;
list1=list1->next;
}else{
tail->next=list2;
list2=list2->next;
}
tail=tail->next;
}
if(list1)
tail->next=list1;
if(list2)
tail->next=list2;
return head;
}