leetcode No148. Sort List

来源:互联网 发布:ecowater 净水器 知乎 编辑:程序博客网 时间:2024/06/06 01:28

Question:

Sort a linked list in O(n log n) time using constant space complexity.

Algorithm:

类似归并排序,程序有注释

Accepted Code:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* sortList(ListNode* head) {        if(head==NULL)            return NULL;        if(head->next==NULL)            return head;                ListNode* pre=head;      //第一段的结尾        ListNode* p1=head;       //p1一次移动1个结点        ListNode* p2=head;       //p2一次移动2个结点        //目标是分成head-pre,p1-p2两段        while(p2!=NULL && p2->next!=NULL){            pre=p1;            p1=p1->next;            p2=p2->next->next;        }        pre->next=NULL;   //head-pre                ListNode* h1=sortList(head);        ListNode* h2=sortList(p1);                return Merge(h1,h2);    }    ListNode* Merge(ListNode* l1,ListNode* l2){        if(l1==NULL)            return l2;        if(l2==NULL)            return l1;        if(l1->val < l2->val){            l1->next=Merge(l1->next,l2);            return l1;        }        else{            l2->next=Merge(l1,l2->next);            return l2;        }        return NULL;    }};


0 0