-
Notifications
You must be signed in to change notification settings - Fork 154
/
Copy pathswap-nodes-in-pairs.js
73 lines (60 loc) · 1.16 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/**
* Swap Nodes in Pairs
*
* Given a linked list, swap every two adjacent nodes and return its head.
* You may not modify the values in the list's nodes, only nodes itself may be changed.
*/
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* Recursion
*
* @param {ListNode} head
* @return {ListNode}
*/
const swapPairsR = head => {
// Empty node or a single node
if (!head || !head.next) {
return head;
}
let prev = head;
let curr = prev.next;
let next = curr.next;
curr.next = prev;
prev.next = swapPairsR(next);
return curr;
};
/**
* Non-Recursion
*
* @param {ListNode} head
* @return {ListNode}
*/
const swapPairs = head => {
// Empty node or a single node
if (!head || !head.next) {
return head;
}
let prev = head;
let curr = head.next;
let next;
head = curr;
while (true) {
next = curr.next;
curr.next = prev;
if (next == null || next.next == null) {
prev.next = next;
break;
}
prev.next = next.next;
curr = next.next;
prev = next;
}
return head;
};
export { swapPairsR, swapPairs };