Insertion Sort is a basic sorting algorithm invented decades ago. And the implementation is simple, too.
Declare a head pointer of a sorted linked-list with initial value NULL. Then, add node to the new list one by one and keep the new list sorted.
class Solution {
public:
ListNode *insertionSortList(ListNode *head)
{
ListNode* res = NULL;
while (head) {
ListNode* next = head -> next;
insertion(&res, res, head);
head = next;
}
return res;
}
void insertion(ListNode** pre, ListNode* head, ListNode* now)
{
while (head) {
if (now -> val < head -> val) {
now -> next = head;
*pre = now;
return;
}
pre = &head -> next;
head = head -> next;
}
*pre = now;
now -> next = head;
}
};