Insert a node at a specific position in a linked list

  • + 0 comments

    Python 3

    However I look at this, the 'position 0' case seems special as you return a different 'head'. The simplest option I could see was to treat it as a separate case.

    I quite like the proposed naming and structure here of 'next_index' being the count, starting from 1, and running through the llist until you find the right point to do the insert... although maybe 'node_count' or something would be more technically correct than 'index'

    def insertNodeAtPosition(llist, data, position):
        
        new_node = SinglyLinkedListNode(data)
        
        if position == 0:
            new_node.next = llist
            return new_head
        
        this = llist
        next_index = 1
        while next_index != position:
            this = this.next
            next_index += 1
        
        new_node.next = this.next
        this.next = new_node
        return llist