原题:
Sort a linked list using insertion sort.
【知识回顾】
插入排序:
- 从第一个元素开始,该元素可以认为已经被排序;
- 取出下一个元素,在已经排序的元素序列中从后向前扫描;
- 如果该元素(已排序)大于新元素,将该元素移到下一位置;
- 重复步骤3,直到找到已排序的元素小于或者等于新元素的位置;
- 将新元素插入到该位置后;
- 重复步骤2~5。
一般情况下我们大多用数组来实现整个过程。所以本题主要的难点在于使用链表进行插入排序。
思路:在处理数组结构时,我们对左边排序好的队列是进行的从后向前的扫描。但我们知道一般链表的问题在于可以指后无法指前,所以我们只能从前往后读。
代码:
/**
* 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 *tmp = head;
ListNode *first;
ListNode *pre = head;
tmp = head->next;
while(tmp){
//have forgotten the primary value of first.
first = head;
for(; first!=tmp; first = first->next){
if(first->val > tmp->val){
pre->next = tmp->next;
tmp->next = first;
head = tmp;
// runtime error because of forgetting change the pointer point to next num waiting to be sorted;
tmp = pre->next;
break;
}
// as long as the later one is larger than tmp, insert it here.
if( first->next->val>tmp->val){
pre->next = tmp->next;
tmp->next =first->next;
first->next = tmp;
tmp = pre->next;
break;
}
}
pre = pre->next;
if(tmp!=NULL) tmp = tmp->next;
}
return head;
}
};
WA