Skip to content

Instantly share code, notes, and snippets.

@JamesJi9277
Created April 7, 2015 13:26
Show Gist options
  • Save JamesJi9277/2def537e3891604f0fac to your computer and use it in GitHub Desktop.
Save JamesJi9277/2def537e3891604f0fac to your computer and use it in GitHub Desktop.
public class Solution{
public int kthtoLast(LinkedListNode head, int k){
if (k < 0|| head == null)
return -1;
LinkedListNode p1 = head;
LinkedListNode p2 = head;
//moving p2 to reach the position length - k.
for(int i = 0; i< k - 1; i++)
{
p2 = p2.next;
}
//p1 and p2 are moving together
while(p2.next != null)
{
p1 = p1.next;
p2 = p2.next;
}
return p1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment