def kth_to_last(head, k):
if not (head or k > -<NUM_LIT:1>):<EOL><INDENT>return False<EOL><DEDENT>p1 = head<EOL>p2 = head<EOL>for i in range(<NUM_LIT:1>, k+<NUM_LIT:1>):<EOL><INDENT>if p1 is None:<EOL><INDENT>raise IndexError<EOL><DEDENT>p1 = p1.next<EOL><DEDENT>while p1:<EOL><INDENT>p1 = p1.next<EOL>p2 = p2.next<EOL><DEDENT>return p2<EOL>
This is an optimal method using iteration.
We move p1 k steps ahead into the list.
Then we move p1 and p2 together until p1 hits the end.