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
Post a Comment