Skip to content

Commit 2a7ca51

Browse files
committed
Swap Node Pairs in List solution
1 parent 56ec0be commit 2a7ca51

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

23-swapNodePairs.js

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
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+
* @return {ListNode}
11+
*/
12+
var swapPairs = function (head) {
13+
if (head === null) {
14+
return null;
15+
}
16+
17+
let result = [];
18+
let thisNode = head;
19+
while (thisNode !== null) {
20+
result.push(thisNode);
21+
thisNode = thisNode.next;
22+
}
23+
24+
for (let i = 1; i < result.length; i += 2) {
25+
console.log("i", i);
26+
let temp = result[i - 1];
27+
result[i - 1] = result[i];
28+
result[i] = temp;
29+
}
30+
31+
for (let i = 0; i < result.length; i++) {
32+
if (i === result.length) {
33+
result[i].next = null;
34+
} else {
35+
result[i].next = result[i + 1];
36+
}
37+
}
38+
39+
return result[0];
40+
};
41+
42+
function ListNode(val, next) {
43+
this.val = val === undefined ? 0 : val;
44+
this.next = next === undefined ? null : next;
45+
}
46+
47+
f = new ListNode(9);
48+
e = new ListNode(8, f);
49+
d = new ListNode(7, e);
50+
c = new ListNode(6, d);
51+
b = new ListNode(5, c);
52+
a = new ListNode(4, b);
53+
54+
console.log(swapPairs(a));

0 commit comments

Comments
 (0)