Skip to content

Commit 9eb22c9

Browse files
solves insertion sort list in java
1 parent 5c47593 commit 9eb22c9

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

Diff for: README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@
131131
| 144 | [Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal) | [![Java](assets/java.png)](src/BinaryTreePreOrderTraversal.java) [![Python](assets/python.png)](python/binary_tree_preorder_traversal.py) | |
132132
| 145 | [Binary Tree Postorder Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal) | [![Java](assets/java.png)](src/BinaryTreePostorderTraversal.java) [![Python](assets/python.png)](python/binary_tree_postorder_traversal.py) | |
133133
| 146 | [LRU Cache](https://leetcode.com/problems/lru-cache) | [![Java](assets/java.png)](src/LRUCache.java) | |
134-
| 147 | [Insertion Sort List](https://leetcode.com/problems/insertion-sort-list) | | |
134+
| 147 | [Insertion Sort List](https://leetcode.com/problems/insertion-sort-list) | [![Java](assets/java.png)](src/InsertionSortList.java) | |
135135
| 148 | [Sort List](https://leetcode.com/problems/sort-list) | | |
136136
| 150 | [Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation) | | |
137137
| 151 | [Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string) | | |

Diff for: src/InsertionSortList.java

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// https://leetcode.com/problems/insertion-sort-list
2+
// T: O(n^2)
3+
// S: O(1)
4+
5+
public class InsertionSortList {
6+
public ListNode insertionSortList(ListNode head) {
7+
if (head == null || head.next == null) return head;
8+
9+
ListNode newHead = new ListNode(0);
10+
ListNode pre = newHead;
11+
ListNode next;
12+
13+
for (ListNode cur = head ; cur != null ; ) {
14+
next = cur.next;
15+
16+
while (pre.next != null && pre.next.val < cur.val) {
17+
pre = pre.next;
18+
}
19+
20+
//insert between pre and pre.next
21+
cur.next = pre.next;
22+
pre.next = cur;
23+
pre = newHead;
24+
cur = next;
25+
}
26+
27+
return newHead.next;
28+
}
29+
}

0 commit comments

Comments
 (0)