class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
ListNode * dummy = new ListNode(-1);
ListNode * pre = dummy;
while(list1 != nullptr && list2 != nullptr )
{
if(list1->val <= list2->val)
{
pre->next = list1;
list1 = list1 ->next;
}
else
{
pre->next = list2;
list2 = list2->next;
}
pre = pre->next;
}
if(list1 != nullptr) pre->next = list1;
if(list2 != nullptr) pre->next = list2;
return dummy->next;
}
};
核心思路是同时循环两个链表,然后值比较,将满足要求的链表接入新链表,接着更新链表索引,然后进入下次循环。如此往复,最后当链表长短不一,即有空指针时,将非空链表接入即可