|
| 1 | +/** |
| 2 | + * 147. Insertion Sort List |
| 3 | + * https://leetcode.com/problems/insertion-sort-list/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given the head of a singly linked list, sort the list using insertion sort, and |
| 7 | + * return the sorted list's head. |
| 8 | + * |
| 9 | + * The steps of the insertion sort algorithm: |
| 10 | + * - Insertion sort iterates, consuming one input element each repetition and growing |
| 11 | + * a sorted output list. |
| 12 | + * - At each iteration, insertion sort removes one element from the input data, finds |
| 13 | + * the location it belongs within the sorted list and inserts it there. |
| 14 | + * - It repeats until no input elements remain. |
| 15 | + * |
| 16 | + * The following is a graphical example of the insertion sort algorithm. The partially |
| 17 | + * sorted list (black) initially contains only the first element in the list. One |
| 18 | + * element (red) is removed from the input data and inserted in-place into the sorted |
| 19 | + * list with each iteration. |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * Definition for singly-linked list. |
| 24 | + * function ListNode(val, next) { |
| 25 | + * this.val = (val===undefined ? 0 : val) |
| 26 | + * this.next = (next===undefined ? null : next) |
| 27 | + * } |
| 28 | + */ |
| 29 | +/** |
| 30 | + * @param {ListNode} head |
| 31 | + * @return {ListNode} |
| 32 | + */ |
| 33 | +var insertionSortList = function(head) { |
| 34 | + const result = new ListNode(0); |
| 35 | + |
| 36 | + while (head) { |
| 37 | + const tail = head; |
| 38 | + let current = result; |
| 39 | + head = head.next; |
| 40 | + |
| 41 | + while (current) { |
| 42 | + if (!current.next || tail.val <= current.next.val) { |
| 43 | + [current.next, tail.next] = [tail, current.next]; |
| 44 | + break; |
| 45 | + } |
| 46 | + current = current.next; |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + return result.next; |
| 51 | +}; |
0 commit comments