原題:
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