Insert a node at a specific position in a linked list

  • + 0 comments
    def insertNodeAtPosition(llist, data, position):
        # Create the new node with the given data
        inserted_node = SinglyLinkedListNode(data)
        # If inserting at the head (position 0)
        if position == 0:
            inserted_node.next = llist
            return inserted_node
        # Traverse the list to find the insertion point
        curr = llist
        curr_pos = 1
        # Loop until the position before the insertion point
        while curr_pos != position:
            curr = curr.next
            curr_pos += 1
        # Insert the new node at the given position
        inserted_node.next = curr.next
        curr.next = inserted_node
        return llist