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.
Test instructions: Merging two sorted lists
The problem is not difficult, but there are a lot of details that need attention, direct sticker code
1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * struct ListNode *next;6 * };7 */8 structlistnode* mergetwolists (structlistnode* L1,structlistnode*L2) {9 structListNode *tmp,*p1,*P2;Ten if(l1==NULL) { Onetmp=L1; Al1=L2; -L2=tmp; - } the if(l1==NULL) - returnL1; -p1=L1; -P2=L2; + while(l1!=NULL) { - if(l2!=null&&l1->val<=l2->val) { + while(l1->next!=null&&l1->next->val<=l2->val) AL1=l1->Next; attmp=L2; -L2=l2->Next; -Tmp->next=l1->Next; -l1->next=tmp; -L1=l1->Next; - } in Else if(l2!=null&&l1->val>l2->val) { -tmp=L1; tol1=L2; +L2=tmp; -p1=L1; the } * Else if(l2==NULL) $ returnP1;Panax Notoginseng } - returnP1; the}
Feel the confusion of writing, re-write again:
1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * struct ListNode *next;6 * };7 */8 structlistnode* mergetwolists (structlistnode* L1,structlistnode*L2) {9 structListNode *tmp,*P1;Ten if(l1==null&&l2==NULL) One returnNULL; A if(l1==NULL) - returnL2; - if(l2==NULL) the returnL1; - if(l1->val>l2->val) { -tmp=L1; -l1=L2; +L2=tmp; - } +p1=L1; A while(l1!=NULL) { at if(l2!=null&&l1->val<=l2->val) { - while(l1->next!=null&&l1->next->val<=l2->val) -L1=l1->Next; -tmp=L2; -L2=l2->Next; -Tmp->next=l1->Next; inl1->next=tmp; - } to Else if(l2==NULL) + returnP1; - } the returnP1; *}
"Leetcode" 21. Merge Sorted Lists