Sort a linked list using insertion sort.
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; } };