题目
代码
/**
* 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) {
ListNode* dummpy_head = new ListNode();
ListNode* dummpy_tail = dummpy_head;
while(l1 != nullptr || l2 != nullptr) {
if(l1 != nullptr && l2 != nullptr) {
int temp1 = l1->val;
int temp2 = l2->val;
if(temp1 > temp2) {
dummpy_tail->next = l2;
dummpy_tail = dummpy_tail->next;
l2 = l2->next;
} else {
dummpy_tail->next = l1;
dummpy_tail = dummpy_tail->next;
l1 = l1->next;
}
} else if(l1 != nullptr) {
dummpy_tail->next = l1;
dummpy_tail = dummpy_tail->next;
l1 = l1->next;
} else if(l2 != nullptr) {
dummpy_tail->next = l2;
dummpy_tail = dummpy_tail->next;
l2 = l2->next;
}
}
dummpy_tail->next = nullptr;
return dummpy_head->next;
}
};