Description:
Sort a linked list using insertion sort.
Analysis:
插入排序,时间复杂度O(N^2)
创建一个dummy node,方便从head开始遍历。
可以结合题目148一起看。
两种解法:
解法一:
断开链表,分成两个链表,链表1是有序链表,链表2是待排序链表,依次将链表2中的元素插入到链表1的有序链表中;
解法二:
不断开链表,依次移动结点,移动结点后,依然保持链表不断开。
这里只需要保存前面已经有序链表的尾指针,因为每次查找最终位置从head头指针查找,不需要保存头指针。
Solution1:
class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
if (head == NULL)
return NULL;
ListNode *cur = head;
ListNode *next = NULL;
ListNode *newlist = NULL;
while (cur) {
next = cur->next;
cur->next = NULL;
if (newlist == NULL) {
cur->next = newlist;
newlist = cur;
} else {
newlist = insertList(newlist, cur);
}
cur = next;
}
return newlist;
}
ListNode* insertList(ListNode* head, ListNode* node) {
if (node->val <= head->val) {
node->next = head;
return node;
}
ListNode *pre = head;
while (pre->next) {
if (pre->next->val >= node->val) {
ListNode *next = pre->next;
pre->next = node;
node->next = next;
break;
}
pre = pre->next;
}
if (pre->next == NULL)
pre->next = node;
return head;
}
};
Solution2:
class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
if (head == NULL || head->next == NULL)
return head;
ListNode *dummy = new ListNode(-1);
dummy->next = head;
ListNode *tail = head, *cur = head->next;
while (cur) {
if (tail->val <= cur->val) {
tail = tail->next;
cur = cur->next;
} else {
ListNode *mov = dummy;
while (mov->next->val < cur->val) {
mov = mov->next;
}
tail->next = cur->next;
cur->next = mov->next;
mov->next = cur;
// cur changed to next cur
// pre donot need change, because only insert the cur node.
cur = tail->next;
}
}
return dummy->next;
}
};