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:
dummy -> 1 -> 2 -> 3 -> 4 -> 5Declare pointers:
prev: Points to the node just before theleftposition. Initially,prevpoints todummy.Move
prevto the node just beforeleft. After the loop,prevpoints to:
prev -> 1Identify important nodes:
start: The first node of the section to be reversed (leftposition), which is2.then: The node immediately afterstart, which is3.
Initial setup looks like this:
dummy -> 1 -> 2 -> 3 -> 4 -> 5
prev start thenStep 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:
dummy -> 1 -> 3 -> 2 -> 4 -> 5
prev then startMove then to the next node after start (node 4):
then -> 4Iteration 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:
dummy -> 1 -> 4 -> 3 -> 2 -> 5
prev startMove then to the next node after start (node 5):
theen -> 5Step 3: Return the Result
After completing the loop, the section from left to right has been reversed. Return the list starting from dummy.next:
1 -> 4 -> 3 -> 2 -> 5Last updated
Was this helpful?