Reverse Linked List II
Description
Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4 Output: 1->4->3->2->5->NULL
Solution(javascript)
const reverseBetween = function (head, m, n) {
let count = 1
let current = head
let part1Tail = null
while (current && count < m) {
if (count === m - 1) {
part1Tail = current
}
count += 1
current = current.next
}
let prev = null
let part2Tail = null
while (current && count <= n) {
if (!part2Tail) {
part2Tail = current
}
const temp = current.next
current.next = prev
prev = current
current = temp
count += 1
}
if (part1Tail) {
part1Tail.next = prev
}
if (part2Tail) {
part2Tail.next = current
}
return part1Tail ? head : (prev || current)
}