I was doing a code of rotating the linked list given the rotation amount on leetcode. I came across interesting problem.
Problem: After assigning the head (H) of the linked list to some other pointer (P) and then rotating the pointer P would make the next element of header pointer H to null.
Example:
If you pass any linked list header to function you can easily reproduce this
My purpose is not to traverse the list. I just wants to understand why does the reference of that pointer change and remains only first value of the listed gets printed?
def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
dummy = head # Pointer pointing to the head of the linked list
pre = None
# Traversing the dummy pointer and keeping backward link to pre pointer
while dummy:
nex = dummy.next
dummy.next = pre
pre = dummy
dummy = nex
while head:
print(head.val) # This would print only the head of the linked list which is 1 in my example of 1,2,3,4,5 it seems like its next is pointing to null
head = head.next
Pass value of the reference pointing elements 1,2,3,4,5 and my head reference would only print the first element of the list Could anyone please explain the reason for this?