题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
题解:
使用普通方法,或者递归,注意新的头节点即可。
1 //使用普通的合并方法 2 class Solution01 { 3 public: 4 ListNode* Merge(ListNode* pHead1, ListNode* pHead2) 5 { 6 if (pHead1 == nullptr || pHead2 == nullptr)return pHead1 == nullptr ? pHead2 : pHead1; 7 ListNode* newHead = nullptr, *p1 = nullptr, *p2 = nullptr; 8 newHead = new ListNode(0); 9 newHead->next = pHead1; 10 p1 = newHead; 11 p2 = pHead2; 12 while (p1->next != nullptr && p2 != nullptr) 13 { 14 if (p1->next->val < p2->val) 15 p1 = p1->next; 16 else 17 { 18 ListNode* temp = p1->next; 19 p1->next = p2; 20 p2 = p2->next; 21 p1->next->next = temp; 22 p1 = p1->next; 23 } 24 } 25 if (p1->next == nullptr && p2 != nullptr) 26 p1->next = p2; 27 return newHead->next; 28 } 29 }; 30 31 //使用递归 32 class Solution { 33 public: 34 ListNode* Merge(ListNode* pHead1, ListNode* pHead2) 35 { 36 if (pHead1 == nullptr || pHead2 == nullptr)return pHead1 == nullptr ? pHead2 : pHead1; 37 ListNode* newHead = nullptr; 38 if (pHead1->val < pHead2->val) 39 { 40 newHead = pHead1; 41 newHead->next = Merge(pHead1->next, pHead2); 42 } 43 else 44 { 45 newHead = pHead2; 46 newHead->next = Merge(pHead1, pHead2->next); 47 } 48 return newHead; 49 } 50 };