-
Notifications
You must be signed in to change notification settings - Fork 0
/
swap-nodes-in-pairs.js
47 lines (31 loc) · 1.03 KB
/
swap-nodes-in-pairs.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
/**
* 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) {
// Initialise a dummy list containing the provided one
let dummyList = new ListNode(null, head);
// Create a copy of the dummy list which we can traverse with
let current = dummyList;
// While there are 2 additional elements remaining
while (current.next && current.next.next) {
// Obtain the nodes to be swapped
const first = current.next;
const second = current.next.next;
// Swap the nodes
first.next = second.next;
second.next = first;
current.next = second;
// Move forward by 2 elements
current = current.next.next;
}
// Return the swapped LinkedList, removing the dummy head
return dummyList.next;
};