-
Notifications
You must be signed in to change notification settings - Fork 0
/
23-swapNodePairs.js
54 lines (47 loc) · 1.14 KB
/
23-swapNodePairs.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
* Definition for singly-linked list.
function ListNode(val, next) {
this.val = (val===undefined ? 0 : val)
this.next = (next===undefined ? null : next)
}
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var swapPairs = function (head) {
if (head === null) {
return null;
}
let result = [];
let thisNode = head;
while (thisNode !== null) {
result.push(thisNode);
thisNode = thisNode.next;
}
for (let i = 1; i < result.length; i += 2) {
console.log("i", i);
let temp = result[i - 1];
result[i - 1] = result[i];
result[i] = temp;
}
for (let i = 0; i < result.length; i++) {
if (i === result.length) {
result[i].next = null;
} else {
result[i].next = result[i + 1];
}
}
return result[0];
};
function ListNode(val, next) {
this.val = val === undefined ? 0 : val;
this.next = next === undefined ? null : next;
}
f = new ListNode(9);
e = new ListNode(8, f);
d = new ListNode(7, e);
c = new ListNode(6, d);
b = new ListNode(5, c);
a = new ListNode(4, b);
console.log(swapPairs(a));