Skip to content

Instantly share code, notes, and snippets.

@chouclee
Created June 19, 2014 06:15
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 chouclee/03cf7577a2ec37c6b311 to your computer and use it in GitHub Desktop.
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
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