Linked List: Insert node at the ith position

Question: Write a function that inserts a node at the ith position of a linked list. Consider the position of the head as the 0th Index

//method to insert node at the ith index
    public void insert(ListNode node, int i){
        //If the list is empty return
        if(head==null){
            return;
        } 
        
        //if the ith index is zero then set it to head
        else if (i==0){
            node.setNext(head);
            head=node;
        } 
        
        else {
            //temp: pointer which traverses the linked list
            ListNode temp= head;
            //index: keep count of number of nodes traversed
            int index=0;
            //traverse the list till the (i-1) index
            while(index!=(i-1)){
                temp=temp.getNext();
                index++;
            }
            //insert the node at the ith index
            node.setNext(temp.getNext());
            temp.setNext(node);
        }
    }

Leave a Reply

PHP JS HTML CSS BASH PYTHON CODE

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: