描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
示例1
输入:
{1,3,5},{2,4,6}
返回值:
{1,2,3,4,5,6}
解法一:谁小指谁
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
if (pHead1 == nullptr) {
return pHead2;
}
if (pHead2 == nullptr) {
return pHead1;
}
ListNode* tempNode;
if (pHead1 -> val < pHead2 -> val) {
tempNode = pHead1;
pHead1 = pHead1 -> next;
}
else {
tempNode = pHead2;
pHead2 = pHead2 -> next;
}
ListNode* result = tempNode;
while(pHead1 != nullptr && pHead2 != nullptr) {
if (pHead1 -> val < pHead2 -> val) {
tempNode -> next = pHead1;
pHead1 = pHead1 -> next;
tempNode = tempNode -> next;
}
else if (pHead1 -> val >= pHead2 -> val) {
tempNode -> next = pHead2;
pHead2 = pHead2 -> next;
tempNode = tempNode -> next;
}
}
if (pHead1 == nullptr) {
tempNode -> next = pHead2;
}
else if(pHead2 == nullptr) {
tempNode -> next = pHead1;
}
return result;
}
};
解法二:递归,又是递归
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
if (pHead1 == nullptr) {
return pHead2;
}
if (pHead2 == nullptr) {
return pHead1;
}
ListNode* tempNode = nullptr;
if (pHead1 -> val < pHead2 -> val) {
tempNode = pHead1;
tempNode -> next = Merge(pHead1 -> next, pHead2);
}
else {
tempNode = pHead2;
tempNode -> next = Merge(pHead1, pHead2 -> next);
}
return tempNode;
}
};