Insert a node at a specific position in a linked list

  • + 2 comments

    Here is a different solution in Java. Took me awhile to figure out the different test secarnios. We should keep track of the element before the given position so that we can modify the next element.

    Node InsertNth(Node head, int data, int position) {
        Node newNode = new Node();
        Node header = head;
    
        // scenario when head is null
        if ( head == null) {
            newNode.data = data;
            return newNode;
        }
    
        newNode.data = data;
        // scenario when we want to insert in the first element on the list
        if (position == 0) {
            newNode.next = head;
            header = newNode;
            return header;
        }
    
        // insert somewhere else 1th, 2th, 3th, etc...
        // should stop the element before the position to keep track of next element and assign to a new element
    
        for (int i=1; i < position && head.next !=null; i++) {
            head = head.next;
        }
        if (head.next != null) {
            newNode.next =  head.next;
            head.next = newNode;
        } else {
            head.next = newNode;
        }
        return header;
    }