LC147. Insertion Sort List
Problem description:
Sort a linked list using insertion sort.
Analysis:
The insertion sort of linked list can be done in O(1) space. In this solution, I create a node, result, to contain the result. The result would be look like the following graph.
-init state-
Original: 1 3 2 4 5
result->null
-first round-
Original: 3 2 4 5
result->1->NULL
I use the next pointer to temporally save the position in the original list. The iter already move to the position in the result list that contains value higher than head->val. Then adjust the pointer in these item to direct head node to result list and move to next item in original list.
1 | /** |
Reference:
https://goo.gl/dzL3m1