Hi guys, for leet code exercise number 328, I have a particular question regarding how the coding works.


This is the instruction: Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list.

The first node is considered odd, and the second node is even, and so on.

Note that the relative order inside both the even and odd groups should remain as it was in the input.

You must solve the problem in O(1) extra space complexity and O(n) time complexity.


This is the code:

public class Solution {
public ListNode oddEvenList(ListNode head) {
if (head == null) return null;
ListNode odd = head, even = head.next, evenHead = even;
while (even != null && even.next != null) {
odd.next = even.next;
odd = odd.next;
even.next = odd.next;
even = even.next;
}
odd.next = evenHead;
return head;
}
}

I'm having a hard time figuring out why head changes whenever odd.next changes.

Case 1: head = [1,2,3,4,5]
For instance, for Case 1, during debugging I found that:

for the first while iteration:
- head = [1,3,4,5]
- odd.next = [3,4,5]
- odd = [3,4,5]
and so on...
until head = [1,3,5], how come? If the variable is not called at all?