Created
April 7, 2015 13:26
-
-
Save JamesJi9277/2def537e3891604f0fac to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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