-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathswapNodesInPairs.js
88 lines (73 loc) · 1.65 KB
/
swapNodesInPairs.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
class ListNode {
constructor(val) {
this.val = val;
this.next = null;
}
}
// const swapPairs = head => {
// if (!head || !head.next) return head;
// let prev = head;
// let curr = head;
// const newHead = curr.next;
// if (!head.next.next || !head.next.next.next) {
// const next = curr.next;
// const temp = next.next;
// next.next = curr;
// curr.next = temp;
// return newHead;
// }
// while (curr && curr.next) {
// const next = curr.next;
// const temp = next.next;
// next.next = curr;
// curr.next = temp;
// prev.next = next;
// prev = curr;
// curr = temp;
// }
// return newHead;
// };
const swapPairs = head => {
if (!head) return head;;
let mid = head;
let left = null;
let right = head.next;
let newHead = head;
while (mid && right) {
if (left) {
left.next = right;
} else {
newHead = right;
}
mid.next = right.next;
right.next = mid;
left = mid;
mid = !mid ? mid : mid.next;
right = !mid ? mid : mid.next;
}
return newHead;
};
/*
specification
input: head of linked list
output: head of linked list after swapping each pair of nodes
constraints: constant extra space, don't modify value in the list's nodes
edge cases:
justification:
to swap pairs in a linked list
explanation
the input linked list will determine the order of the output linked list
visualization
approximation
break connections and reset them
verification
implementation
*/
const a1 = new ListNode(1);
const a2 = new ListNode(2);
const a3 = new ListNode(3);
const a4 = new ListNode(4);
a1.next = a2;
a2.next = a3;
a3.next = a4;
console.log(swapPairs(a1));