Getting run error in test 1

Hi, I tried to optimise the solution by reducing the number of while loops to one.
However, I am getting a run error in test 0. Can you please explain why?

My code -

    Node current = this.head;
	Node res = null;
	int i = 0;

	while(current != null){
		if( i == k) res = this.head;
		current = current.next;
		if(res != null) res = res.next;
		i++;
	}

	return res.data;

Hey @aditikanaujia72_4531383e6a802ab3 Your logic is wrong bcoz you have starting updating res from the moment you got to kth position from start but you need kth from last. So make changes accordingly.
PS : You have to use slow and fast pointer approach.

Hey @aditikanaujia72_4531383e6a802ab3 There is a minor change in your code. You just need to put
this statement
if(res != null) res = res.next;
before
if( i == k) res = this.head;
and change condition to i == k - 1;
since your code is failing testcase like :
1 2 3 4 5 -1
5

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.