21. 合并两个有序链表 - 力扣(LeetCode)
非递归
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
if(list1 == nullptr && list2 != nullptr)
return list2;
if(list2 == nullptr && list1 != nullptr)
return list1;
//记录头部的链表
ListNode* head = new ListNode(0);
ListNode* task = head;//链接后面用的链表
while(list1 && list2)
{
if(list1->val <= list2->val)
{
task->next = list1;
list1 = list1->next;
}
else
{
task->next = list2;
list2 = list2->next;
}
task = task->next;
}
task->next = (list1 == nullptr ? list2 : list1);
return head->next;
}
};