Input: 1->2->3->4->5->6->7->8->null
void method(list){
if(list.head == null) return;
Node slow_ref = list.head;
Node fast_ref = list.head;
Node prevS = null;
Node prevF = null;
while(fast_ref != null && fast_ref.next != null){
prevS = slow_ref;
slow_ref = slow_ref.next;
prevF = fast_ref;
fast_ref = fast_ref.next.next;
}
prevS.next = slow_ref.next;
prevF.next.next = slow_ref;
slow_ref.next = null;
}
After the while loop terminates
slow_ref points to 5
fast_ref points to null
prevS points to 4
prevF points to 7
After the execution of next 3 lines after while loop
Final linked list will be
1 -> 2 -> 3 -> 4 -> 6 -> 7 -> 8 -> 5 -> null
If you have any doubt, feel free to ask in the comments.
Get Answers For Free
Most questions answered within 1 hours.