-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathswap_nodes_in_pairs.js
More file actions
50 lines (45 loc) · 1.49 KB
/
swap_nodes_in_pairs.js
File metadata and controls
50 lines (45 loc) · 1.49 KB
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
var swapPairs = function (head) {
// Dummy node
const dummy = new ListNode(0);
// Point the next of dummy node to the head
dummy.next = head;
// This node will be used to traverse the list
let current = dummy;
// Loop until we reach to the second last node
while (current.next !== null && current.next !== undefined && current.next.next !== null) {
// First node of the pair
let first = current.next;
// Second node of the pair
let second = current.next.next;
// Point the next of first node to the node after second node
first.next = second.next;
// Now the current node's next should be the second node
current.next = second;
// Linking the original second node to the first node
current.next.next = first;
// Move the pointer two nodes ahead
current = current.next.next;
}
return dummy.next;
};
function ListNode(val, next) {
this.val = (val === undefined ? 0 : val)
this.next = (next === undefined ? null : next)
}
function printList(node) {
let list = [];
while (node != null) {
list.push(node.val);
node = node.next
}
console.log(list.join(" "));
}
let headNode = new ListNode(1);
headNode.next = new ListNode(2);
headNode.next.next = new ListNode(3);
headNode.next.next.next = new ListNode(4);
printList(swapPairs(headNode));
headNode = undefined;
printList(swapPairs(headNode));
headNode = new ListNode(1);
printList(swapPairs(headNode));