148. Sort List(체인 테이블의 병합 정렬, 느린 포인터로 partition)

1365 단어 LeetCode
Sort a linked list in O(n log n) time using constant space complexity.
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
AC 코드:
class Solution {
public:
    ListNode* sortList(ListNode* head) {
        if(!head||!head->next)
            return head;
        ListNode* slow=head;
        ListNode* fast=head->next;
        while(fast&&fast->next){
            slow=slow->next;
            fast=fast->next->next;
        }
        //       
        //      ,             1   2      
        //   merge  
        fast=slow->next;
        slow->next=NULL;
        return merge(sortList(head),sortList(fast));
    }
    
    ListNode* merge(ListNode* l1,ListNode* l2){
        ListNode dummy(0);
        ListNode* helper=&dummy;
        //       =。=
        while(l1&&l2){
            if(l1->valval){
                helper->next=l1;
                l1=l1->next;
            }
            else{
                helper->next=l2;
                l2=l2->next;
            }
            helper=helper->next;
        }
        if(l1)
            helper->next=l1;
        else
            helper->next=l2;
        return dummy.next;
    }
};

좋은 웹페이지 즐겨찾기