...

/

Reverse a Sub-list (medium)

Reverse a Sub-list (medium)

Problem Statement

Given the head of a LinkedList and two positions ‘p’ and ‘q’, reverse the LinkedList from position ‘p’ to ‘q’.

Try it yourself

Try solving this question here:

import java.util.*;
class ListNode {
int value = 0;
ListNode next;
ListNode(int value) {
this.value = value;
}
}
class ReverseSubList {
public static ListNode reverse(ListNode head, int p, int q) {
// TODO: Write your code here
return head;
}
public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);
ListNode result = ReverseSubList.reverse(head, 2, 4);
System.out.print("Nodes of the reversed LinkedList are: ");
while (result != null) {
System.out.print(result.value + " ");
result = result.next;
}
}
}

Solution

The problem follows the In-place Reversal of a LinkedList pattern. We can use a similar approach as discussed in Reverse a LinkedList. Here are the steps we need to follow:

  1. Skip the first p-1 nodes, to reach the node at position p.
  2. Remember the node at position p-1 to be used later to connect with
...