Insert a node at a specific position in a linked list HackerRank

 public static SinglyLinkedListNode insertNodeAtPosition(SinglyLinkedListNode head, int data, int pos) {

        SinglyLinkedListNode temp=head;
        SinglyLinkedListNode old;
        SinglyLinkedListNode newNode=new SinglyLinkedListNode(data);
        int i=0;
        while(i<pos-1){
            temp=temp.next;
            i++;
        }
        old=temp.next;
        temp.next=newNode;
        newNode.next=old;
        return head;
        
           // Write your code here

    }

/*Time O(N)[Worst Case] Space O(1)
We will traverse to one position before the actual index where we want to insert the node.
After that, we will store the reference of a further node in a node named old.
and change the value of temp next pointing now to the new node
and new node next will now point to the node named old.*/


Comments

Popular posts from this blog

Java Date And Time HackerRank

Recursive Sequence Geeks For Geeks Problem Of The Day 12-02-2024

Minimum Indices HackerEarth