Created
June 26, 2014 06:31
-
-
Save JoyceeLee/2fa8f900432f8759c79f 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
/*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