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

[LeetCode] Sort List

时间:2015-08-17 17:30:45      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   

Sort List

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

解题思路:

题意为以常量存储空间和O(nlogn)时间复杂度来排序链表。

可以用合并排序法,并用双指针法来找到中间节点。

产生一个头结点方便编码。

/**
 * 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) {
        ListNode* myHead = new ListNode(0);
        myHead->next = head;
        myHead = mergeSort(myHead);
        head = myHead->next;
        delete myHead;
        return head;
    }
    
    ListNode* mergeSort(ListNode* head){
        if(head->next==NULL || head->next->next==NULL){
            return head;
        }
        ListNode* one = head, *two = head;
        while(two->next!=NULL && two->next->next!=NULL){
            one = one->next;
            two = two->next->next;
        }
        two = new ListNode(0);
        two->next = one->next;
        one->next = NULL;
        
        one = mergeSort(head);
        two = mergeSort(two);
        one = merge(one, two);
        return one;
    }
    
    ListNode* merge(ListNode* head1, ListNode* head2){
        ListNode* head = new ListNode(0);
        ListNode* tail = head;
        while(head1->next!=NULL && head2->next!=NULL){
            if(head1->next->val > head2->next->val){
                tail->next = head2->next;
                head2->next = head2->next->next;
            }else{
                tail->next = head1->next;
                head1->next = head1->next->next;
            }
            tail = tail->next;
        }
        if(head1->next!=NULL){
            tail->next = head1->next;
        }
        if(head2->next!=NULL){
            tail->next = head2->next;
        }
        delete head1;
        delete head2;
        return head;
    }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

[LeetCode] Sort List

标签:c++   leetcode   

原文地址:http://blog.csdn.net/kangrydotnet/article/details/47726177

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