147. Insertion Sort List
Last updated
Last updated
/**
* 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) {
return NULL;
}
ListNode* newNode = new ListNode(0);
while (head) {
ListNode* curr = head;
head = head->next;
//回到原點
ListNode* pre = newNode;
//移動pre到適當位置: 盡可能移動到小於curr的, list的最右端
while (pre->next && pre->next->val <= curr->val) {
pre = pre->next;
}
curr->next = pre->next;
pre->next = curr;
}
head = newNode->next;
delete newNode;
return head;
}
}