码迷,mamicode.com
首页 > 其他好文 > 详细

[Linked List]Sort List

时间:2015-12-12 18:43:07      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

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

[Linked List]Sort List

标签:

原文地址:http://www.cnblogs.com/zengzy/p/5041483.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!