Skip to content

Commit b0ba108

Browse files
authored
Create 1721-swapping-nodes-in-a-linked-list.js
1 parent c2fd3c7 commit b0ba108

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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+
};

0 commit comments

Comments
 (0)