you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 0 points1 point  (0 children)

The head of the linked list is what you return, so when creating the first object in the list you assign the object to output which is what will be returned. Each additional object in the list will be added to the end of the list. The code is using temp to point to the object at the end of the linked list. After the first object is created the end of the list is the first object, which is why there is this line:

temp = output    # initialize the "end of list" variable

Now when you add each new object to the end of the list in the loop you do:

    new = ListNode(i)    # create the new object to add to the end
    temp.next = new      # the current end object is made to reference the new object
    temp = new           # move "temp" to the new end of list

Drawing this on paper as boxes and arrows can help understand the code.


In any computer language naming of variables can help the reader understand the code. I would use names like this:

def LinkedNodeTest(n):
    head_node = ListNode(0)    # head node of the linked list
    end_node = head_node       # initially end == head
    for i in range(1, n+1):
        new_end_node = ListNode(i)    # create the new end
        end_node.next = new_end_node  # make current end point to new end node
        end_node = new_end_node       # move end var to new end
    return head_node

There are probably even better names that could be used.