Topic source: Niuke.com
programming link
Topic description:
Input two monotonically increasing linked lists, and output the linked list after combining the two linked lists. Of course, we need the combined linked list to satisfy the monotonically non-decreasing rule.
Parse:
Use recursive thinking.
Code:
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if(pHead1 == nullptr)
return pHead2;
if(pHead2 == nullptr)
return pHead1;
return (pHead1->val > pHead2->val)?(pHead2->next = Merge(pHead1,pHead2->next),pHead2 ):
(pHead1->next = Merge(pHead1->next,pHead2),pHead1);
}
};
Running time: 3ms; Occupied memory: 356k
Code analysis: first compare the size, determine who is smaller, who is the head node, and the next node of the head node continues to be obtained by merge.
, indicating that the merge is performed first, and then the head node is returned.