1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * ListNode *next;6 * ListNode (int x): Val (x), Next (NULL) {}7 * };8 */9 classSolution {Ten Public: OneListNode *mergetwolists (ListNode *l1, ListNode *L2) { A if(l1==0)returnL2; - if(l2==0)returnL1; -ListNode *start=0, *end=0; the if(l1->val<l2->val) { -Start=end=L1; -L1=l1->Next; - } + Else{ -Start=end=L2; +L2=l2->Next; A } at while(l1!=0&&l2!=0){ - if(l1->val<l2->val) { -end->next=L1; -L1=l1->Next; - } - Else{ inend->next=L2; -L2=l2->Next; to } +End=end->Next; - } the if(l1==0) *end->next=L2; $ ElsePanax Notoginsengend->next=L1; - returnstart; the } +};
Test instructions: Merges two ordered linked lists into an ordered list and returns.
Idea: no recursion! The first value compares the size, and start points to the small one, as the last return address. Li keeps comparing the L2 to the end pointer after each comparison, and end starts from start. Finally, the two linked lists will be strung together and ordered. Analogy: Two hands holding an orderly poker, each pick out the hands of the smallest points, put on the table, and finally they from the bottom to the top of the stack in an orderly manner. Then one hand shines first, then you can put the rest of the cards directly on the table.
Leetcode Merge Sorted Lists merging sort