题目描述:
Sort a linked list using insertion sort.
Example
题目思路:
Given 1->3->2->0->null
, return 0->1->2->3->null
.
这题用dummy head,并且把link断成两节考虑:前面是已经sort好了的,后面是需要被sort的。然后找出当前ptr应该在前面那一截中被安插的位置,放好这个ptr就好了。
Mycode(AC = 129ms):
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @return: The head of linked list.
*/
ListNode *insertionSortList(ListNode *head) {
// write your code here
if (head == NULL || head->next == NULL) {
return head;
}
ListNode *dummy = new ListNode(INT_MIN);
ListNode *tmp = dummy;
// cur = 1, next = 3
ListNode *cur = head, *next = head->next;
while (cur) {
next = cur->next;
tmp = dummy;
// find the position to insert current ptr
while (tmp->next && tmp->next->val < cur->val) {
tmp = tmp->next;
}
cur->next = tmp->next;
tmp->next = cur;
cur = next;
}
return dummy->next;
}
};