File tree 1 file changed +52
-0
lines changed
one-question-per-day/20201020
1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change
1
+ const reorderList = head => {
2
+ if ( ! head || ! head . next ) {
3
+ return head ;
4
+ }
5
+
6
+ const half = findHalf ( head ) ;
7
+ const secondHalf = half . next ;
8
+ half . next = null ;
9
+
10
+ let newSecondHalf = reverseLinkedList ( secondHalf ) ;
11
+
12
+ // 合并
13
+ let currentHead = head ;
14
+ while ( currentHead && newSecondHalf ) {
15
+ const x = currentHead . next ;
16
+ const y = newSecondHalf . next ;
17
+ currentHead . next = newSecondHalf ;
18
+ newSecondHalf . next = x ;
19
+ currentHead = x ;
20
+ newSecondHalf = y ;
21
+ }
22
+ }
23
+
24
+ // 寻找链表中间值
25
+ function findHalf ( head ) {
26
+ let fast = head ;
27
+ let slow = head ;
28
+ while ( fast && fast . next ) {
29
+ fast = fast . next . next ;
30
+ slow = slow . next ;
31
+ }
32
+
33
+ return slow ;
34
+ }
35
+
36
+ // 翻转链表
37
+ function reverseLinkedList ( head ) {
38
+ if ( ! head || ! head . next ) {
39
+ return head ;
40
+ }
41
+
42
+ let nextNode = head . next ;
43
+ head . next = null ;
44
+ while ( nextNode ) {
45
+ const temp = nextNode . next ;
46
+ nextNode . next = head ;
47
+ head = nextNode ;
48
+ nextNode = temp ;
49
+ }
50
+
51
+ return head ;
52
+ }
You can’t perform that action at this time.
0 commit comments