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.
I use the "runner" technique. We make a runner pointer move k elements into the list. Then we create a curr pointer. We move both pointers 1 step at a time until runner is at the end. When this happens, curr will be at the kth to last element.
Runtime: O(n)
Space Complexity: O(1)
intGetNode(Nodehead,intk){Nodecurr=head;Noderunner=head;/* Move runner into the list by k elements */for(inti=0;i<k;i++){runner=runner.next;}/* Move both pointers */while(runner.next!=null){curr=curr.next;runner=runner.next;}returncurr.data;}
Get Node Value
You are viewing a single comment's thread. Return to all comments →
O(1) space complexity Java Iterative solution.
From my HackerRank solutions.
I use the "runner" technique. We make a runner pointer move k elements into the list. Then we create a curr pointer. We move both pointers 1 step at a time until runner is at the end. When this happens, curr will be at the kth to last element.
Runtime: O(n)
Space Complexity: O(1)
Let me know if you have any questions.