File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Definition for singly-linked list.
3+ * function ListNode(val, next) {
4+ * this.val = (val===undefined ? 0 : val)
5+ * this.next = (next===undefined ? null : next)
6+ * }
7+ */
8+ /**
9+ * @param {ListNode } head
10+ * @param {number } k
11+ * @return {ListNode }
12+ */
13+ const swapNodes = function ( head , k ) {
14+ const dummy = new ListNode ( )
15+ dummy . next = head
16+ const arr = [ ]
17+ let cur = head
18+ while ( cur ) {
19+ arr . push ( cur )
20+ cur = cur . next
21+ }
22+ const n = arr . length
23+ if ( k < 1 || k > n ) return dummy . next
24+ let first = arr [ k - 1 ] , second = arr [ n - k ]
25+
26+ arr [ k - 1 ] = second
27+ arr [ n - k ] = first
28+
29+ dummy . next = arr [ 0 ]
30+ let pre = arr [ 0 ]
31+ for ( let i = 1 , len = arr . length ; i < len ; i ++ ) {
32+ const tmp = arr [ i ]
33+ pre . next = tmp
34+ pre = tmp
35+ }
36+
37+ pre . next = null
38+
39+ return dummy . next
40+ } ;
You can’t perform that action at this time.
0 commit comments