-
Notifications
You must be signed in to change notification settings - Fork 0
/
92-leetcode-reverse-linked-list-ii.js
63 lines (53 loc) · 1.5 KB
/
92-leetcode-reverse-linked-list-ii.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
const reverseBetween = (head, m, n) => {
if (m >= n) return head;
let currentNode = head;
let previousNode = head;
let temp = null,
temp2 = null,
tempStart = null;
let countm = 0,
countn = 0;
if (!currentNode.next) return head;
let startNode = head;
//Move previousNode to m and currentNode to m+1
let flag;
while (countm < m && currentNode !== null) {
if (!flag) flag = 1; //need to check whether m is whithin range
//advance pointer and do nothing
startNode = previousNode;
previousNode = currentNode;
currentNode = currentNode.next;
countm++;
}
if (!flag) return head; //m doesn't exist within range
//edge case when m=1
if (startNode === previousNode) {
while (countn < n - m && currentNode !== null) {
//save original location
temp = currentNode.next;
//switch pointers
currentNode.next = previousNode;
startNode.next = temp;
previousNode = currentNode;
//advance node
currentNode = temp;
countn++;
}
return previousNode;
}
// when m>1
while (flag === 1 && countn < n - m && currentNode !== null) {
//save original locations for advancement after switching pointers
temp = currentNode.next;
temp2 = previousNode;
//switch pointers
currentNode.next = startNode.next;
startNode.next = currentNode;
previousNode.next = temp;
//advance prev & cur using the original locations
previousNode = temp2;
currentNode = temp;
countn++;
}
return head;
};