Sort a linked list using insertion sort.
Solution:
Code:
<span style="font-size:14px;">/**
* 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 || head->next == NULL) return head;
ListNode *begin = head, *nextNode, *before, *after;
head = head->next;
//attention
begin->next = NULL;
while (head != NULL) {
nextNode = head->next;
if (head->val <= begin->val) {
head->next = begin;
begin = head;
} else {
before = begin;
while (before->next != NULL && before->next->val < head->val)
before = before->next;
if (before->next == NULL) {
before->next = head;
head->next = NULL;
} else {
after = before->next;
before->next = head;
head->next = after;
}
}
head = nextNode;
}
return begin;
}
};</span>