DIY: Reverse Linked List II

Solve the interview question "Reverse Linked List II" in this lesson.

Problem statement

Suppose you are given the head of a singly linked list with n nodes. Your task is to reverse the list’s nodes from the position left to position right, and return the reversed list.

Note that left and right are positive integers, where 1 <= left <= right <= n.

Input

The input will be the head of a linked list and two positive integers, left and right. The following are examples of the inputs:

// Sample Input 1:
head = 5 -> 7 -> 1 -> 9 -> 15 -> 90 -> 101 -> 200 -> 3 -> 63
left = 2
right = 7

// Sample Input 2:
head = 3
left = 1
right = 1

Output

The output should be the modified list. The following are examples of the outputs:

// Sample Output 1:
5 -> 101 -> 90 -> 15 -> 9 -> 1 -> 7 -> 200 -> 3 -> 63

// Sample Output 2:
3

Level up your interview prep. Join Educative to access 80+ hands-on prep courses.