将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例 1:
输入:l1 = [1,2,4], l2 = [1,3,4] 输出:[1,1,2,3,4,4]
示例 2:
输入:l1 = [], l2 = [] 输出:[]
示例 3:
输入:l1 = [], l2 = [0] 输出:[0]
提示:
- 两个链表的节点数目范围是
[0, 50]
-100 <= Node.val <= 100
l1
和l2
均按 非递减顺序 排列
代码如下
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
typedef struct ListNode ListNode;
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2) {
//在创建链表之前:处理链表为空的情况
if(list1==NULL)
{
return list2;
}
if(list2==NULL)
{
return list1;
}
ListNode*newHead=NULL,*newTail=NULL;
ListNode*l1=list1;
ListNode*l2=list2;
while(l1 && l2)
{
if(l1->val<l2->val)
{
if(newHead==NULL)
{
newHead=newTail=l1;
}
else
{
newTail->next=l1;
newTail=newTail->next;
}
l1=l1->next;
}
else
{
if(newHead==NULL)
{
newHead=newTail=l2;
}
else
{
newTail->next=l2;
newTail=newTail->next;
}
l2=l2->next;
}
}
if(l1)
{
newTail->next=l1;
}
if(l2)
{
newTail->next=l2;
}
return newHead;
}