Search code examples
pythonpython-3.xlinked-listsingly-linked-list

How to initialize a LinkedList head to None(as done in C++)?


How to initialize head in this implementation of LinkedList in python? I know a Node class can be defined that will make things easier.But I am trying to do in this way(like in C++).

class LinkedList:
   def __init__(self,val=None,next=None):
       self.val = val
       self.next = next

Solution

  • If you just have this one class, then it actually serves as a Node class, and you lack the container class that would have the head member.

    This has as consequence that the program will have to manage the head itself. The variable that will be used to reference a linked list could be that head variable, but that also means an empty list will be represented by None.

    For instance:

    head = None  # Empty list
    head = LinkedList(1, head)  # Add the first node to it
    head = LinkedList(2, head)  # Prepend the second node to it
    head = LinkedList(3, head)  # Prepend the third node to it.
    
    # Print the values in the list:
    node = head
    while node:
        print(node.val, end=" ")
        node = node.next
    print()
    

    Output will be:

    3 2 1