Skip to content

Instantly share code, notes, and snippets.

@JoyceeLee
Created June 26, 2014 06:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoyceeLee/2fa8f900432f8759c79f to your computer and use it in GitHub Desktop.
Save JoyceeLee/2fa8f900432f8759c79f to your computer and use it in GitHub Desktop.
/*2.2 Implement an algorithm to find the kth to last element of a singly linked list.*/
public class Solution {
public int findKth(ListNode head) {
ListNode kth = head;
ListNode end = head;
int i=0;
while(i<k) {
end = end.next;
}
while(end!=null) {
end = end.next;
kth = kth.next;
}
return kth.val;
}
}
/* the 'Remove Nth Node From End of List' on leetcode
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode p = head;
ListNode q = head;
int i=0;
while(i<n){
q = q.next;
i++;
}
if(q==null){
head = head.next;
} else {
while(q.next!=null){
p = p.next;
q = q.next;
}
p.next = p.next.next;
}
return head;
}
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment