forked from JoshCrozier/leetcode-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0092-reverse-linked-list-ii.js
42 lines (38 loc) · 1017 Bytes
/
0092-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
/**
* 92. Reverse Linked List II
* https://leetcode.com/problems/reverse-linked-list-ii/
* Difficulty: Medium
*
* Given the head of a singly linked list and two integers left and right where
* left <= right, reverse the nodes of the list from position left to position
* right, and return the reversed list.
*/
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @param {number} left
* @param {number} right
* @return {ListNode}
*/
var reverseBetween = function(head, left, right) {
const result = new ListNode(0, head);
let previous = result;
let currentIndex = 1;
while (currentIndex++ < left) {
previous = previous.next;
}
const tail = previous.next;
while (left++ < right) {
const next = tail.next;
tail.next = next.next;
next.next = previous.next;
previous.next = next;
}
return result.next;
};