Home > Software design >  One confusion when creating linked list with list
One confusion when creating linked list with list

Time:11-07

I am using below function to creating a linked list, head1, with the list, ll. It works very well. But I just confuse why using the commented part, the linked list cannot be created successfully, compared with its above three lines? What is the detailed reason?

def head_list_to_linkedlist(ll):
    head1 = ListNode(ll[0])
    for val in ll[1:]:
        node = ListNode(val)
        node.next = head1
        head1 = node
        #ListNode(val).next = head1
        #head1 = ListNode(val)
    return head1

CodePudding user response:

The commented code creates two nodes. The first one is lost because it is not captured with a name, while the second one has nothing to do with the first, so in the end it is no different from only doing head1 = ListNode(val)

If your purpose is to somehow shorten the code a bit, then take these actions:

  • Make sure that the ListNode constructor can take an optional second argument which will be the value of the next attribute of the constructed node:

    class ListNode:
        def __init__(self, val nxt=None):
            self.val = val
            self.next = nxt
    
  • Then, use that argument to prefix values to the linked list. To make sure you get them in the right order, iterate the ll list in reverse:

    def head_linkedlist_to_list(ll):
        head = None
        for val in reversed(ll):
            head = ListNode(val, head)  # the old head becomes the next reference
        return head
    

This has as additional advantage that it will also work when ll is empty.

  • Related