-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
42 lines (32 loc) · 708 Bytes
/
index.js
File metadata and controls
42 lines (32 loc) · 708 Bytes
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
const debug = require('debug')('swapPairs');
class ListNode {
constructor(val) {
this.val = val;
this.next = null;
}
}
// create a list: 1 -> 2 -> 3 -> 4 -> 5 -> null
const headNode = new ListNode(1);
let currentNode = headNode;
for (let i = 2; i <= 5; i += 1) {
currentNode.next = new ListNode(i);
currentNode = currentNode.next;
}
const swapPairs = (head) => {
let pre = new ListNode();
const h = pre;
pre.next = head;
while (pre.next && pre.next.next) {
const pp = pre;
const a = pre.next;
const b = a.next;
const t = b.next;
b.next = a;
a.next = t;
pp.next = b;
pre = a;
}
return h.next;
};
const h1 = swapPairs(headNode);
debug(h1);