"Idea 1" recursion
1 /*2 struct ListNode {3 int val;4 struct ListNode *next;5 listnode (int x):6 val (x), Next (NULL) {7 }8 };*/9 classSolution {Ten Public: Onelistnode* Merge (listnode* pHead1, listnode*pHead2) A { - if(PHead1 = =NULL) - returnpHead2; the Else if(PHead2 = =NULL) - returnPHead1; -listnode* res =NULL; - if(Phead1->val <= phead2->val) { +res =PHead1; -Res->next = Merge (phead1->Next, pHead2); +}Else{ Ares =pHead2; atRes->next = Merge (phead1,phead2->next); - } - returnRes; - } -};
"Train of Thought 2" non-recursive, create a new list and save the head node, the original two linked list to be compared sequentially inserted into the new linked list, and finally will have the remaining linked list directly connected.
1 /*2 struct ListNode {3 int val;4 struct ListNode *next;5 listnode (int x):6 val (x), Next (NULL) {7 }8 };*/9 classSolution {Ten Public: Onelistnode* Merge (listnode* pHead1, listnode*pHead2) { A if(PHead1 = =NULL) - returnpHead2; - Else if(PHead2 = =NULL) the returnPHead1; -listnode* res =NULL; -listnode* cur =NULL; - while(PHead1! = NULL && pHead2! =NULL) { + if(Phead1->val <= phead2->val) { - if(res = =NULL) +res = cur =PHead1; A Else{ atCur->next =PHead1; -Cur = cur->Next; - } -PHead1 = phead1->Next; -}Else{ - if(res = =NULL) inres = cur =pHead2; - Else{ toCur->next =pHead2; +Cur = cur->Next; - } thePHead2 = phead2->Next; * } $ }Panax Notoginseng if(PHead1 = =NULL) { -Cur->next =pHead2; the } + if(PHead2 = =NULL) { ACur->next =PHead1; the } + returnRes; - } $};
[Sword means offer] 16. Merge two sorted lists