[Python] What is the difference when assigning an object like a LinkedList to a variable...

Discussão em 'Python' iniciado por Stack, Março 26, 2025.

  1. Stack

    Stack Membro Participativo

    I was working on this problem from HackerRank trying to insert an element at the tail of a linked list and I have to return the head of the node.

    def insertNodeAtTail(head, data):
    if head is None:
    head = SinglyLinkedListNode(data)
    return head
    current_head = head
    while current_head.next:
    current_head = current_head.next
    current_head.next = SinglyLinkedListNode(data)
    return head


    SinglyLinkedListNode is a class for creating nodes with 2 methods: data which gives value to the node, and next which allows us to move on to the next node.

    The code above works but my understanding is, if we mess or tweak with current_head, the changes will appear on head too (because that's how assigning works in Python). But the code is working perfectly. If I use return current_head, the answer is wrong. I did something similar such as

    a = [1,2,3,4,5,6]
    b = a
    for i in range(5):
    b.append(i)


    And both array a and array b are identical and prints [1,2,3,4,5,6,0,1,2,3,4]. I'd appreciate any help I can get please. This inconsistency is messing with my head because the idea for inserting at the end of the tail is clearly easy but I keep getting worried about having to return the head of the node (and I can't do that if I keep misunderstanding whether I am changing anything to the LL).

    Thank you in advance!

    Continue reading...

Compartilhe esta Página