AlgoMaster Logo

Reverse Linked List II

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Iterative Reversal with Extra Space

Intuition:

This approach leverages an extra data structure to reverse the segment of the linked list. We first traverse the list to the position where the reversal starts, collect nodes in an array for the part to be reversed, reverse the array, and finally rebuild the linked list using this array.

Steps:

  1. Traverse the list to find the part of the list that needs to be reversed.
  2. Store nodes to be reversed into an array.
  3. Reverse the array contents.
  4. Reconnect the nodes before, within, and after the reversed segment accordingly.

Code:

2. Iterative In-Place Reversal

Intuition:

Instead of using extra space, this approach manages all operations directly within the list structure. The key is to carefully manage pointers to reverse the sublist in place by detaching and reattaching nodes.

Steps:

  1. Traverse the linked list to the starting position of reversal.
  2. Reverse the sublist by changing pointers in place.
  3. Reconnect the reversed section to the remainder of the list.

Code: