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

[LeetCode] Insertion Sort List

时间:2015-06-25 16:59:35      阅读:94      评论:0      收藏:0      [点我收藏+]

标签:

Sort a linked list using insertion sort.

 

Hide Tags
 Linked List Sort
 
 
分析:把链表分成两部分:排好序的和为排序的,排好序的以NULL结尾,cur插在preInsertion和insertion之间,next保存cur->next.
        另外,注意dummy的使用简化了插入头结点的情况。

时间复杂度O(n^2),空间O(1) 

 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
    public:
        ListNode* insertionSortList(ListNode* head)
        {   
            if(head == NULL)
                return NULL;

            ListNode dummy(INT_MIN);
            dummy.next = head;

            ListNode* preInsertion = NULL;
            ListNode* insertion = NULL;
            ListNode* cur = head->next;
            head->next = NULL;//break the sorted and unsorted
            ListNode* next = NULL;

            while(cur)
            {   
                preInsertion = & dummy;
                insertion = dummy.next;

                //find the right position
                while(insertion != NULL && cur->val >= insertion->val)
                {
                    preInsertion = preInsertion->next;
                    insertion = insertion->next;
                }

#if 0
                if(insertion == NULL)//cur is max, don‘t need to move it
                {
                    next = cur->next;//just store cur first;
                    preInsertion->next = cur; 
                    cur->next = NULL;
                    cur = next;
                }
                else
                {
                    next = cur->next;//just store cur first;
                    preInsertion->next = cur; 
                    cur->next = insertion;
                    cur = next;
                }
#endif
                next = cur->next;//just store cur first;
                preInsertion->next = cur;
                cur->next = insertion;
                cur = next;


            }
            return dummy.next;
        }
};

 

[LeetCode] Insertion Sort List

标签:

原文地址:http://www.cnblogs.com/diegodu/p/4600224.html

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