Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Iterator;
- import java.util.LinkedList;
- public class findNthToLastElement {
- public static int findNth(LinkedList<Integer> list,int n){
- if (n == 0){
- return 0;
- }
- Iterator<Integer> itr = list.iterator();
- int index = list.size()+1 - n;
- int num = 0;
- for (int i = 0; i < index; i++){
- num = itr.next();
- }
- return num;
- }
- public static void main (String argv []){
- LinkedList<Integer> list = new LinkedList<Integer>();
- list.add(1);
- list.add(2);
- list.add(5);
- list.add(2);
- list.add(5);
- list.add(20);
- list.add(4);
- System.out.println(list);
- System.out.println(findNth(list, 7));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement