Input: head =1->2->3->4->5->nullOutput: 3->4->5->1->2->nullExplanation: The list was transformed in several steps.1. First step, swap 1 and 3 i.e.3–>2–>1–>4–>5–>null2. Second step, swap 2 and 4 i.e.3–>4–>1–>2–>5–>null3. last step, swap 1 and 5, i.e.3–>4–>5–>2–>1–>null
We can observe that each step involves reversing a sublist of size 3 starting from the current node and then advancing the head to the next node for the subsequent iteration. Reversing a 3-element linked list is straightforward and can be achieved with just two swaps (or by using two temporary variables). The most challenging aspect of this problem is maintaining the correct pointer to the head of the list. Below is a simple yet effective implementation.