解题思路

归并排序

解题代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* merge(ListNode* l1, ListNode* l2) {
        ListNode fake(-1);
        auto p = &fake;
        while(true) {
            if(l1 ==NULL || l2 == NULL) break;
            if(l1->val <= l2->val ) p->next = l1, p = l1,l1 = l1->next,p->next = NULL;
            else {
                p->next = l2, p = l2,l2 = l2->next,p->next = NULL;
            }
            // p = p
        }
        if(l1) p->next = l1;
        if(l2) p->next = l2;
        return fake.next;
    }  
};