题意
按非降序合并两个链表
方法
归并排序
代码
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
ListNode * head = nullptr;
ListNode * ans = nullptr;
bool flag = true;
while (list1 != nullptr && list2 != nullptr) {
ListNode * tmpNode;
if (list1->val < list2->val) {
tmpNode = new ListNode(list1->val);
list1 = list1->next;
}
else {
tmpNode = new ListNode(list2->val);
list2 = list2->next;
}
if (flag) {
head = tmpNode;
flag = false;
ans = head;
}
else {
head->next = tmpNode;
head = head->next;
}
}
while (list1 != nullptr) {
if (flag) {
head = list1;
flag = false;
ans = head;
}
else {
head->next = list1;
head = head->next;
}
list1 = list1->next;
}
while (list2 != nullptr) {
if (flag) {
head = list2;
flag = false;
ans = head;
}
else {
head->next = list2;
head = head->next;
}
list2 = list2->next;
}
return ans;
}