We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Hi. We start from the head position, not the tail. I basically make 1 pointer walk k elements into the list. At the beginning of the while loop, we have 1 pointer at the head of the list and 1 pointer k elements into the list. Now, we move both pointers 1 step at a time. When the runner pointer (the pointer that was inside the list) reaches the end of the list, that means we have our other pointer reach the kth-to-last element.
If this still doesn't make sense, I recommend drawing a linked list with paper and pencil and walking through the code with it to better visualize it.
Get Node Value
You are viewing a single comment's thread. Return to all comments →
Hi. We start from the head position, not the tail. I basically make 1 pointer walk k elements into the list. At the beginning of the while loop, we have 1 pointer at the head of the list and 1 pointer k elements into the list. Now, we move both pointers 1 step at a time. When the runner pointer (the pointer that was inside the list) reaches the end of the list, that means we have our other pointer reach the kth-to-last element.
If this still doesn't make sense, I recommend drawing a linked list with paper and pencil and walking through the code with it to better visualize it.
HackerRank solutions.