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

148. Sort List

时间:2017-12-20 21:55:26      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:mem   osi   using   slow   实现   ref   lin   ddl   public   

148. Sort List

题目

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

解答Accept

  • 实现之前看了思路,想想先就用递归实现
  • 结果模仿别人写都有5个bug,感觉没有用心啊!!!
// Definition for singly - linked list.
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

// sort list
class Solution {
public:

    ListNode* findMiddle(ListNode* head)
    {
        ListNode* slow = head;
        ListNode* fast = head->next;
        while (fast&&fast->next) //bug1 ||
        {
            slow = slow->next;
            fast = fast->next->next;
        }
        return slow;
    }

    ListNode* MergeList(ListNode* left, ListNode*right)
    {
        if (left==NULL)
        {
            return right;
        }
        if (right==NULL)
        {
            return left;
        }

        ListNode* temp = new ListNode(0);
        ListNode* temp_head = temp;  //bug2 头指针移动
        while (left&&right)
        {
            if (left->val<right->val)
            {
                temp->next = left;  //bug3 顺序反了
                left = left->next;
                
            }
            else
            {
                temp->next = right;
                right = right->next;
            }
            temp = temp->next;
        }

        if (left) //bug4 if->while
        {
            temp->next = left;
        }
        if (right)
        {
            temp->next = right;
        }

        return temp_head->next;

    }
    ListNode* sortList(ListNode* head) {

        if (!head||!head->next)  // Line 57: member access within null pointer of type 'struct ListNode'
        {
            return head;  //bug5 忘记取!
        }
        
        ListNode *middle = findMiddle(head);


        ListNode* left=sortList(middle->next);

        middle->next = NULL;
        ListNode* right = sortList(head);

        ListNode *ret=MergeList(left, right);
        return  ret;
    }
};

题目来源:148. Sort List,讨论里面非递归实现

148. Sort List

标签:mem   osi   using   slow   实现   ref   lin   ddl   public   

原文地址:http://www.cnblogs.com/ranjiewen/p/8075675.html

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