Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

One confusion when creating linked list with list

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading