[Linked List]Sort List

otal Accepted: 59473 Total Submissions: 253637 Difficulty: Medium

 

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) {}
 * };
 */
class Solution {
public:
    ListNode* mergeSortList(ListNode* head1,ListNode* head2)
    {
        if(head1==NULL){
            return head2;
        }
        if(head2==NULL){
            return head1;
        }
        ListNode* newHead = head1->val < head2->val ?  head1:head2;
        newHead->next = head1->val < head2->val ? mergeSortList(head1->next,head2):mergeSortList(head1,head2->next);
        return newHead;
    }
    int getListLength(ListNode *head)
    {
        int cnt = 0;
        while(head){
            cnt++;
            head = head->next;
        }
        return cnt;
    }
    ListNode* sortList(ListNode* head) {
        int len = getListLength(head);
        if(len<=1){
            return head;
        }
        int cnt = len/2;
        ListNode* p = head,*pre=NULL;
        while(cnt--){
            pre = p;
            p = p->next;
        }
        ListNode* head2 = p;
        pre->next = NULL;
        ListNode* head1 = sortList(head);
        head2 = sortList(head2);
        return mergeSortList(head1,head2);
    }
};
Next challenges: (M) Insertion Sort List
posted @ 2015-12-12 16:59  zengzy  阅读(194)  评论(0编辑  收藏  举报
levels of contents