Let’s explain step by step 🐇
how to reverse part of a linked list from left = 2
to right = 4
using an example 1
:
Input:
The linked list: 1 -> 2 -> 3 -> 4 -> 5
We need to reverse the section between positions left = 2
and right = 4
.
Step 1: Initialization
Create a dummy node to make edge cases easier to handle. The list now looks like this:
Declare pointers:
prev
: Points to the node just before theleft
position. Initially,prev
points todummy
.Move
prev
to the node just beforeleft
. After the loop,prev
points to:
Identify important nodes:
start
: The first node of the section to be reversed (left
position), which is2
.then
: The node immediately afterstart
, which is3
.
Initial setup looks like this:
Step 2: Reverse the Sublist
We loop right - left
times (2 times in this case) to reverse the section between left
and right
.
Iteration 1:
Update links:
start.next = then.next
: Node2
(start
) now points to4
(skipping3
).then.next = prev.next
: Node3
(then
) now points to2
.prev.next = then
: Node1
(prev
) now points to3
.
The list now looks like this:
Move then
to the next node after start
(node 4
):
Iteration 2:
Update links:
start.next = then.next
: Node2
(start
) now points to5
(skipping4
).then.next = prev.next
: Node4
(then
) now points to3
.prev.next = then
: Node1
(prev
) now points to4
.
The list now looks like this:
Move then
to the next node after start
(node 5
):
Step 3: Return the Result
After completing the loop, the section from left
to right
has been reversed. Return the list starting from dummy.next
:
Last updated