Problem
Sort a linked list using insertion sort.
A graphical example of insertion sort. The partial sorted list (black) initially contains only the first element in the list. With each iteration one element (red) is removed from the input data and inserted in-place into the sorted list
Algorithm of Insertion Sort:
- Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list.
- At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there.
- It repeats until no input elements remain.
Example 1:
1 |
|
Example 2:
1 |
|
Explanation
-
First create a dummy node, and we need to have a
cur
pointer points at the dummy node, andlstPtr
pointer points at the original list’s node for iterating. -
While
lstPtr
is not null, we starts fromlstPtr
’s node, compare it with everycur.next
’s node in the dummy list starts from the beginning of dummy list, here we also need a while loop to achieve this. Ifcur.next
is null, orcur.next
’s value is greater thanlstPtr
’s value, then we break out this inner while loop, and addlstPtr
’s node to our dummy list.
Solution
1 |
|