1. Description of the problem
Merge sorted linked lists and return it as a new list. The new list should is made by splicing together the nodes of the first of the lists.
Tags: Linked List
Similar Problems: (H) Merge K Sorted Lists (E) Merge Sorted Array (m) Sort List (m) Shortest Word Distance II
2. Answer your ideas3. Code
1 structListNode {2 intVal;3ListNode *Next;4ListNode (intx): Val (x), Next (NULL) {}5 };6 classSolution {7 Public:8listnode* mergetwolists (listnode* L1, listnode*L2) {9 if(NULL = =L1)Ten { One returnL2; A } - Else if(NULL = =L2) - { the returnL1; - } -ListNode *phead =NULL; -ListNode *pt =NULL; + while(Null! = L1 && NULL! =L2) - { + if(L1->val > l2->val) A { at if(pt = =NULL) - { -PT =< - } - Else - { inPt->next =L2; -PT =L2; to } +L2 = l2->Next; -Pt->next =NULL; the if(NULL = =phead) * { $Phead =pt;Panax Notoginseng } - } the Else + { A if(pt = =NULL) the { +PT =L1; - } $ Else $ { -Pt->next =L1; -PT =L1; the - } WuyiL1 = l1->Next; thePt->next =NULL; - if(NULL = =phead) Wu { -Phead =pt; About } $ Else - { - - } A } + } the if(NULL! =L1) - { $ while(NULL! =L1) the { thePt->next =L1; thePT =L1; theL1 = l1->Next; -Pt->next =NULL; in } the } the Else About { the while(NULL! =L2) the { thePt->next =< +PT =L2; -L2 = l2->Next; thePt->next =NULL;Bayi } the } the returnPhead; - } -};
4. Reflection
. Merge Sorted Lists