Insert a node at a specific position in a linked list

  • + 0 comments

    def insertNodeAtPosition(llist, data, position):

    dummy = SinglyLinkedListNode(data)
    curr = llist
    i=0
    while curr is not None:
        i = i+1
        next_node = curr.next # save next node 
        if i == position:
            curr.next = dummy  #set current nodes next pointer to dummy
            dummy.next = next_node #set dummy's next pointer to next_node
        curr = next_node    #move to the next_node
    return llist