将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1==nullptr)
{
return l2;
}
if(l2==nullptr)
{
return l1;
}
ListNode head;
head.next=nullptr;
ListNode *k=&head;
ListNode *cur1=l1;
ListNode *cur2=l2;
while(cur1&&cur2)
{
if(cur1->val<=cur2->val)
{
k->next=cur1;
cur1=cur1->next;
}
else
{
k->next=cur2;
cur2=cur2->next;
}
k=k->next;
}
if(cur1==nullptr)
{
k->next=cur2;
}
else
{
k->next=cur1;
}
return head.next;
}
};