Insert a Node at the Tail of a Linked List

  • + 3 comments

    I did it non recursively, calling a function multiple times unless necessary would be inefficient.

    def Insert(head, data):
        if head == None:
            return Node(data,None)
        temp = head
        while temp != None:
            prevFinalNode=temp
            temp = temp.next
        prevFinalNode.next = Node(data,None)
        return head
    

    Also you could have used elif instead of else>if/else as such

    def Insert(head, data):
        if head == None:
            return Node(data, None)
        elif head.next == None:
            head.next = Node(data,None)
        else:
            Insert(head.next,data)
        return head
    

    The code looks more readable this way I think, sorry for the nitpicking.