Insert a node at a specific position in a linked list

  • + 0 comments

    kinda wish you could thumbs-down the questions that pretend to cater to some languages and just don't. I guess it's python again then...

    def insertNodeAtPosition(llist, data, position):
        newNode = SinglyLinkedListNode(data)
        if position == 0:
            newNode.next = llist
            return newNode
        insertAt = llist
        while position > 1:
            position-=1
            insertAt = insertAt.next
        newNode.next = insertAt.next
        insertAt.next = newNode
        return llist