Kth node from the last

https://ide.codingblocks.com/s/62022

(line 181 to 191)

https://hack.codingblocks.com/contests/c/511/469

my code is showing run error , i m trying to reverse the link list and then find the kth element from the front.

plz reply…

Hi Ayush, you do not need to reverse the linked list, instead take two pointers and use them.
Initialise the the 2 pointers let’s say x & y, both pointing towards head of the list.
Now move y k times as : y = y-> next ;
after you have moved y k times, now move both x & y together until y-> next != NULL
when y-> next becomes NULL, x will point on (k+1)th element from end in the list.
so one more time execute x = x-> next.
Now x is pointing on kth node from last.

Hope this helps :slight_smile:

1 Like

i know but i was trying implementing my approach to see if it was correct.And i found the problem . Thanks

1 Like