File tree 1 file changed +68
-0
lines changed
1 file changed +68
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * https://leetcode-cn.com/problems/reorder-list/
3
+ *
4
+ * 143. 重排链表
5
+ *
6
+ * Medium
7
+ *
8
+ * 92ms 97.62%
9
+ *
10
+ * 40.7mb 83.33%
11
+ */
12
+ const reorderList = head => {
13
+ if ( ! head || ! head . next ) {
14
+ return head ;
15
+ }
16
+
17
+ // 寻找列表的中间值
18
+ let slow = head ;
19
+ let fast = head ;
20
+
21
+ while ( fast && fast . next ) {
22
+ fast = fast . next . next ;
23
+ slow = slow . next ;
24
+ }
25
+
26
+ // 翻转后半段
27
+ const secondHalf = slow . next ;
28
+ slow . next = null ;
29
+
30
+ let newSecondHalf = reverseLinkedList ( secondHalf ) ;
31
+
32
+ // 合并
33
+ let currentHead = head ;
34
+ while ( currentHead && newSecondHalf ) {
35
+ const x = currentHead . next ;
36
+ const y = newSecondHalf . next ;
37
+ currentHead . next = newSecondHalf ;
38
+ newSecondHalf . next = x ;
39
+ currentHead = x ;
40
+ newSecondHalf = y ;
41
+ }
42
+ }
43
+ /**
44
+ * 1 -> 2 -> 3 -> 4 -> 5
45
+ * 一、
46
+ * head: 1
47
+ * nextNode: 2 -> 3 -> 4 -> 5
48
+ *
49
+ * 二、
50
+ * head: 2 -> 1
51
+ * nextNode: 3 -> 4 -> 5
52
+ */
53
+ function reverseLinkedList ( head ) {
54
+ if ( ! head || ! head . next ) {
55
+ return head ;
56
+ }
57
+
58
+ let nextNode = head . next ;
59
+ head . next = null ;
60
+ while ( nextNode ) {
61
+ const temp = nextNode . next ;
62
+ nextNode . next = head ;
63
+ head = nextNode ;
64
+ nextNode = temp ;
65
+ }
66
+
67
+ return head ;
68
+ }
You can’t perform that action at this time.
0 commit comments