题目:
Sort a linked list using insertion sort.
解答:
/**
* 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 || !head->next) {
return head;
}
ListNode guardNode(0);
ListNode *pGuardNode = &guardNode;
pGuardNode->next = head;
ListNode *cur = head;
while (cur->next) {
ListNode *tmp = pGuardNode;
while (tmp != cur && tmp->next->val <= cur->next->val) {
tmp = tmp->next;
}
if (tmp->next->val > cur->next->val) {
ListNode *a = tmp->next;
ListNode *b = cur->next->next;
tmp->next = cur->next;
cur->next->next = a;
cur->next = b;
} else {
cur = cur->next;
}
}
return pGuardNode->next;
}
};