Skip to content

Commit b813706

Browse files
authored
Create 92-reverse-linked-list-ii.js
1 parent 8b9f72a commit b813706

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

92-reverse-linked-list-ii.js

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* function ListNode(val) {
4+
* this.val = val;
5+
* this.next = null;
6+
* }
7+
*/
8+
/**
9+
* @param {ListNode} head
10+
* @param {number} m
11+
* @param {number} n
12+
* @return {ListNode}
13+
*/
14+
const reverseBetween = function(head, m, n) {
15+
// Empty list
16+
if (head == null) {
17+
return null;
18+
}
19+
20+
// Move the two pointers until they reach the proper starting point
21+
// in the list.
22+
let cur = head, prev = null;
23+
while (m > 1) {
24+
prev = cur;
25+
cur = cur.next;
26+
m--;
27+
n--;
28+
}
29+
30+
// The two pointers that will fix the final connections.
31+
let con = prev, tail = cur;
32+
33+
// Iteratively reverse the nodes until n becomes 0.
34+
let third = null;
35+
while (n > 0) {
36+
third = cur.next;
37+
cur.next = prev;
38+
prev = cur;
39+
cur = third;
40+
n--;
41+
}
42+
43+
// Adjust the final connections as explained in the algorithm
44+
if (con != null) {
45+
con.next = prev;
46+
} else {
47+
head = prev;
48+
}
49+
50+
tail.next = cur;
51+
return head;
52+
};

0 commit comments

Comments
 (0)