前言
Insertion Sort List算是Linked List tag下的一道中等难度的题吧,可以用来复习链表的选择排序操作。解法很固定,没什么讨论的余地。
题目
https://leetcode.com/problems/insertion-sort-list/
Sort a linked list using insertion sort.
排序一个链表,指定必须采用插入排序算法。
分析
插入排序是比较基础的一种排序算法,遍历元素,把它插入到该插入的位置,这里有一个网页动画可以帮助理解这个算法的具体过程。(同时也提供了其他一些常见的排序算法的可视化图形表示)
这里需要注意的是,为了避免处理一些比较繁琐的边界条件问题,我们使用一个Dummy Head节点来作为表头节点。代码写的比较清楚,直接show code.
代码
class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
ListNode* Dummy = new ListNode(0);
Dummy -> next = head;
ListNode* pre = Dummy;
ListNode* cur = Dummy->next;// which is just head
while (cur) {// cur != NULL
if (cur -> next && cur -> next -> val < cur -> val) {
while (pre -> next && pre -> next -> val < cur -> next -> val)
pre = pre -> next;
//Now we get where to insert. Insert cur -> next after pre.
ListNode* tmp = pre -> next;
pre -> next = cur -> next;
cur -> next = cur -> next -> next;
pre -> next -> next = tmp;
/* Move pre back to Dummy. */
pre = Dummy;
}
else cur = cur -> next;
}
return Dummy->next;
}
};