File tree Expand file tree Collapse file tree 2 files changed +42
-1
lines changed Expand file tree Collapse file tree 2 files changed +42
-1
lines changed Original file line number Diff line number Diff line change 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 ) | |
134134| 147 | [ Insertion Sort List] ( https://leetcode.com/problems/insertion-sort-list ) | [ ![ Java] ( assets/java.png )] ( src/InsertionSortList.java ) | |
135- | 148 | [ Sort List] ( https://leetcode.com/problems/sort-list ) | | |
135+ | 148 | [ Sort List] ( https://leetcode.com/problems/sort-list ) | [ ![ Java ] ( assets/java.png )] ( src/SortList.java ) | |
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 ) | | |
138138| 152 | [ Maximum Product Subarray] ( https://leetcode.com/problems/maximum-product-subarray ) | | |
Original file line number Diff line number Diff line change 1+ // https://leetcode.com/problems/sort-list
2+ // T: O(N log(N))
3+ // S: O(log(N))
4+
5+ public class SortList {
6+ public ListNode sortList (ListNode head ) {
7+ if (head == null || head .next == null ) return head ;
8+ ListNode mid = getMid (head );
9+ ListNode left = sortList (head );
10+ ListNode right = sortList (mid );
11+ return merge (left , right );
12+ }
13+
14+ ListNode merge (ListNode list1 , ListNode list2 ) {
15+ ListNode dummyHead = new ListNode ();
16+ ListNode tail = dummyHead ;
17+ while (list1 != null && list2 != null ) {
18+ if (list1 .val < list2 .val ) {
19+ tail .next = list1 ;
20+ list1 = list1 .next ;
21+ } else {
22+ tail .next = list2 ;
23+ list2 = list2 .next ;
24+ }
25+ tail = tail .next ;
26+ }
27+ tail .next = (list1 != null ? list1 : list2 );
28+ return dummyHead .next ;
29+ }
30+
31+ ListNode getMid (ListNode head ) {
32+ ListNode midPrev = null ;
33+ while (head != null && head .next != null ) {
34+ midPrev = (midPrev == null ? head : midPrev .next );
35+ head = head .next .next ;
36+ }
37+ ListNode mid = midPrev .next ;
38+ midPrev .next = null ;
39+ return mid ;
40+ }
41+ }
You can’t perform that action at this time.
0 commit comments