File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * 时间复杂度:O(n)
3
+ * 空间复杂度:O(1)
4
+ */
5
+ const swapNodes = function ( head , k ) {
6
+ let length = 0 ;
7
+
8
+ let x = null ;
9
+ let xPreHead = null ;
10
+
11
+ let currentHead = head ;
12
+ while ( currentHead ) {
13
+ length ++ ;
14
+ if ( length === k - 1 ) {
15
+ xPreHead = currentHead ;
16
+ }
17
+ if ( length === k ) {
18
+ x = currentHead ;
19
+ }
20
+ currentHead = currentHead . next ;
21
+ }
22
+
23
+ const xSufHead = x . next ;
24
+
25
+ let k2 = length - k ;
26
+ let y = null ;
27
+ let yPreHead = null ;
28
+ currentHead = head ;
29
+ while ( k2 -- ) {
30
+ yPreHead = currentHead ;
31
+ currentHead = currentHead . next ;
32
+ }
33
+ y = currentHead ;
34
+ const ySufHead = y . next ;
35
+
36
+ const xval = x . val ;
37
+ const yval = y . val ;
38
+
39
+ x . val = yval ;
40
+ y . val = xval ;
41
+
42
+ return head ;
43
+ } ;
3186
You can’t perform that action at this time.
0 commit comments