首页 > 其他 > 详细

LeetCode OJ - Sort List

时间:2014-05-16 05:46:52      阅读:339      评论:0      收藏:0      [点我收藏+]

题目:

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

解题思路:

  复杂度为O(n* logn) 的排序算法有:快速排序、堆排序、归并排序。对于链表这种数据结构,使用归并排序比较靠谱。递归代码如下:

代码:

  

bubuko.com,布布扣
/**
 * 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 || head->next == NULL) {
            return head;
        }
        
        /*找到链表中间的元素*/
        ListNode* p_middle = head;
        ListNode* p_last = head->next;
        while(p_last != NULL && p_last->next != NULL){
            p_middle = p_middle->next;
            p_last = p_last->next->next;
        }
        
        /*划分为左右两部分*/
        ListNode* p_left = head;
        ListNode* p_right = p_middle->next;
        p_middle->next = NULL;
        
        /*对左右两部分分别进行排序*/
        p_left = sortList(p_left);
        p_right = sortList(p_right);
        
        /*合并*/
        ListNode* p_head = NULL;
        if(p_left->val < p_right->val){
            p_head = p_left;
            p_left = p_left->next;
        }else{
            p_head = p_right;
            p_right = p_right->next;
        }
        
        ListNode* p_current = p_head;
        while (p_left != NULL && p_right != NULL) {
            if (p_left->val < p_right->val){
                p_current->next = p_left;
                p_left = p_left->next;
            } else {
                p_current->next = p_right;
                p_right = p_right->next;
            }
            p_current = p_current->next;
        }
        if (p_left != NULL) p_current->next = p_left;
        if (p_right != NULL) p_current->next = p_right;
        
        return p_head;
    }
};
bubuko.com,布布扣

 

LeetCode OJ - Sort List,布布扣,bubuko.com

LeetCode OJ - Sort List

原文:http://www.cnblogs.com/dongguangqing/p/3726297.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!