合并两个有序链表
思路: 判断是否有空链表
if (list1 == nullptr) return list2;
if (list2 == nullptr) return list1;
如果没有空链表
1.先比较 2个链表头元素的大小,确定新链表的起始地址,确定后将地址后移(因为当前元素已经进入新链表了,没有再比一次的必要)
2.比较后面2个元素的大小,将小的元素地址加入链表中。之后地址后移
3.当有一个地址为空时,新地址的的后面直接拼接上最后的。
代码如下:
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
ListNode* temp = nullptr;
ListNode* r_temp = nullptr;
if (list1 == nullptr) return list2;
if (list2 == nullptr) return list1;
if (list1->val > list2->val)
{
temp = list2;
r_temp = list2;
list2 = list2->next;
}
else
{
temp = list1;
r_temp = list1;
list1 = list1->next;
}
while (list1 != nullptr && list2 != nullptr)
{
temp->next = (list1->val < list2->val ? list1 : list2);
if (temp->next == list1)
{
temp = list1;
list1 = list1->next;
}
else {
temp = list2;
list2 = list2->next;
}
}
if (list1 == nullptr)
{
temp->next = list2;
}
else {
temp->next = list1;
}
return r_temp;
}
};