Get Node Value HackerRank Problem Solving

 public static int getNode(SinglyLinkedListNode head, int pos) {

           SinglyLinkedListNode temp=head;
            int count=0;
            while(temp!=null){
                count++;
                temp=temp.next;
                
            }
            int d=count-pos-1;
            int i=0;
            temp=head;
            while(i<d){
                temp=temp.next;
                i++;
            }
            System.out.println(temp.data);// Write your code here
            return temp.data;
    }

/*Time O(N) Space O(1)
Here we traverse and find out the total count of nodes in the list.
Then we subtract position and find out the index upto which
we have to traverse from the start.
Once reached we print that data value or return it.*/

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