Created
June 19, 2014 06:15
-
-
Save chouclee/03cf7577a2ec37c6b311 to your computer and use it in GitHub Desktop.
[CC150][2.2] Implement an algorithm to find the nth to last element of a singly linked 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
import java.util.LinkedList; | |
public class nthToLast { | |
public static<Item> Item find(LinkedList<Item> list, int n) { | |
int N = list.size(); | |
if ( n < 1 || n > N) return null; | |
int idx = N - n; | |
return list.get(idx); | |
} | |
public static void main (String[] args) { | |
LinkedList<Integer> test = new LinkedList<Integer>(); | |
for (int i = 0; i < 10; i++) | |
test.add(i); | |
System.out.println(find(test, 0)); | |
System.out.println(find(test, 1)); | |
System.out.println(find(test, 7)); | |
System.out.println(find(test, 10)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment