Insert a Node at the Tail of a Linked List

  • + 2 comments

    Insert a Node at the Tail of a Linked List Pyton 3

    def insertNodeAtTail(head, data):
        new_node = SinglyLinkedListNode(data)
        
        # If the linked list is empty, the new node becomes the head
        if head is None:
            head = new_node
            return head
        
        # Traverse to the end of the linked list
        current_node = head
        while current_node.next is not None:
            current_node = current_node.next
        
        # Add the new node at the end of the linked list
        current_node.next = new_node
        
        return head
    

    This function inserts a new node at the end of a singly linked list in Python, taking two arguments as input: head and data. If the linked list is empty, the new node becomes the head and the function returns head. If the list is not empty, the function traverses to the end and adds the new node.