0

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?

  • 1
    Since you are using the word "pointer" so many times in throughout the question, I'd point out that all of these are references, not pointers – DeepSpace May 03 '22 at 18:52
  • Right. After your first statement. `dummy` and `head` both reference the same object. That does not make a copy. When you change `dummy`, you also change `head`. You don't need to change the object to traverse the list. – Tim Roberts May 03 '22 at 18:56
  • Python does not have pointers. Python has *names*. They are just "labels" that you attach to objects. The label can be easily moved from object to object and an object can have many labels. – Bakuriu May 03 '22 at 19:03

1 Answers1

0

You don't need to modify any link node to traverse the list.

def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
    dummy = head
    pre = None
    while dummy:
        nex = dummy.next
        pre = dummy
        dummy = nex
    while head:
        print(head.val) # This would print only the head of the linked list         
        head = head.next

Or, even simpler:

    while dummy:
        pre, dummy = dummy, dummy.next
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
  • Thanks for replying but I do understand that though my purpose is not to reverse the linked list but I want to know the behavior of python referencing. I have updated my question please feel free to comment on that – pujan prajapati May 08 '22 at 23:16