[Python] Head seems to be acting strangely if its value is observed [closed]

Discussão em 'Python' iniciado por Stack, Fevereiro 13, 2025.

  1. Stack

    Stack Membro Participativo

    I'm solving Leetcode problem 19.

    # head is a singly-linked list
    temp = head
    temp = temp.next
    print("Node: " + str(temp))


    This outputs the contents of a linked list. It looks something like Node: ListNode{val: 3, next: ListNode{...}}.

    However, if I add the line print(temp.val) to the end of the code, I get an AttributeError: 'NoneType' object has no attribute 'val'.

    Even more strangely, stdout now shows the single line "Node: None".

    It seems like temp becomes None if its value is going to be observed in the future. I can't think of any explanation for this behavior.

    Continue reading...

Compartilhe esta Página