Untitled
unknown
plain_text
a year ago
1.2 kB
9
Indexable
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
if(!list1 && !list2)
return nullptr;
else if(list2 && !list1)
return list2;
else if (list1 && !list2)
return list1;
ListNode* result = nullptr, *cur = nullptr;
if(list1->val < list2->val)
{
result = cur = list1;
list1 = list1->next;
}
else
{
result = cur = list2;
list2 = list2->next;
}
while(list1 && list2)
{
if(list1->val < list2->val)
{
auto temp = list1->next;
cur->next = list1;
cur = cur->next;
list1 = temp;
}
else
{
auto temp = list2->next;
cur->next = list2;
cur = cur->next;
list2 = temp;
}
}
if(list1)
cur->next = list1;
if(list2)
cur->next = list2;
return result;
}
};Editor is loading...
Leave a Comment