Skip to content

Commit e486ac2

Browse files
committed
Add solution #147
1 parent 7200200 commit e486ac2

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,7 @@
149149
144|[Binary Tree Preorder Traversal](./0144-binary-tree-preorder-traversal.js)|Easy|
150150
145|[Binary Tree Postorder Traversal](./0145-binary-tree-postorder-traversal.js)|Easy|
151151
146|[LRU Cache](./0146-lru-cache.js)|Medium|
152+
147|[Insertion Sort List](./0147-insertion-sort-list.js)|Medium|
152153
148|[Sort List](./0148-sort-list.js)|Medium|
153154
149|[Max Points on a Line](./0149-max-points-on-a-line.js)|Hard|
154155
151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium|

solutions/0147-insertion-sort-list.js

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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

Comments
 (0)