Created
June 10, 2014 19:44
-
-
Save rioshen/c71dd3e012d863acb4c6 to your computer and use it in GitHub Desktop.
Find Nth to the last element in the list.
This file contains hidden or 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
/** | |
* Problem: Find the nth to the end of the linked list. | |
*/ | |
public class FindNth { | |
/** | |
* Solution: | |
* A simple math - nth to the end equals to: the length - n | |
* from the beginning. | |
* We can first calculate the length of the linked list then print | |
* the (length - n) node from the beginning. | |
* | |
* Analysis: | |
* Time Complexity: O(N), where N means the length of the list. | |
* Space Complexity: O(1) | |
*/ | |
public static int getNth(ListNode head, int n) { | |
if (head == null || n < 0) return -1; | |
/* Calculate the length of the linked list */ | |
int length = 0; | |
ListNode current = head; | |
while (current != null) { | |
current = current.next; | |
length++; | |
} | |
int nth = length - n; | |
current = head; | |
while (nth != 0) { | |
current = current.next; | |
nth--; | |
} | |
return current.value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment