-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathswapNodesInPairs
40 lines (38 loc) · 989 Bytes
/
swapNodesInPairs
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
/**
* 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) {
var current = head, prev= null,temp,node1,node2,workAround;
while(current) {
if(!current.next) {
break;
}
temp = current.next.next; // temp : 3 => 4
node1 = current; // node1: 1 => 2 => 3 => 4
node2 = current.next; // node2: 2 => 3 => 4
node1.next = temp;// 1 => 3 => 4
node2.next = node1; // node2: 2 => 1 => 3 => 4
if(prev) {
prev.next = node2;
}
if(!prev) {
workAround = node2;
}
prev = node1;
current = temp; // jumping by two
}
if(workAround) {
workAround.next = head;
} else {
workAround = head;
}
return workAround;
};