File tree Expand file tree Collapse file tree 2 files changed +30
-1
lines changed Expand file tree Collapse file tree 2 files changed +30
-1
lines changed Original file line number Diff line number Diff line change 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 ) | | |
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments