File tree 2 files changed +60
-0
lines changed
2 files changed +60
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * lc148 Sort list (https://leetcode.com/problems/sort-list/)
3
+ * Definition for singly-linked list.
4
+ * function ListNode(val) {
5
+ * this.val = val;
6
+ * this.next = null;
7
+ * }
8
+ */
9
+ /**
10
+ * @param {ListNode } head
11
+ * @return {ListNode }
12
+ */
13
+ const merge = ( head1 , head2 ) => {
14
+ let fake = new ListNode ( null ) , head = fake ;
15
+
16
+ while ( head1 !== null && head2 !== null ) {
17
+ if ( head1 . val < head2 . val ) {
18
+ head . next = head1 ;
19
+ head1 = head1 . next ;
20
+ } else {
21
+ head . next = head2 ;
22
+ head2 = head2 . next ;
23
+ }
24
+ head = head . next ;
25
+ }
26
+
27
+ if ( head1 !== null ) {
28
+ head . next = head1 ;
29
+ }
30
+
31
+ if ( head2 !== null ) {
32
+ head . next = head2 ;
33
+ }
34
+
35
+ return fake . next ;
36
+ } ;
37
+
38
+ var sortList = function ( head ) {
39
+ if ( head === null || head . next === null ) {
40
+ return head ;
41
+ }
42
+
43
+ let slow = head , fast = head , prev = null ;
44
+ while ( fast !== null && fast . next !== null ) {
45
+ prev = slow
46
+ slow = slow . next ;
47
+ fast = fast . next . next ;
48
+ }
49
+ prev . next = null ;
50
+
51
+ const l1 = sortList ( head ) ;
52
+ const l2 = sortList ( slow ) ;
53
+
54
+ return merge ( l1 , l2 ) ;
55
+ } ;
56
+
Original file line number Diff line number Diff line change 1
1
# Linked List
2
2
3
+ ## Some Tips
4
+ ### Get the middle point of linked list
5
+ Use two pointers, one slow, one fast.
3
6
4
7
## Questions
5
8
- [ Remove Duplicates From Sorted List] ( https://leetcode.com/problems/remove-duplicates-from-sorted-list/ )
9
+ - [ Sort List] ( https://leetcode.com/problems/sort-list/ )
You can’t perform that action at this time.
0 commit comments