您的位置:首页 > 其它

[LeetCode] Insertion Sort List

2015-06-25 16:14 344 查看
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: