Advertisement
spmwilson

findNthToLastElementInLinkedList

Mar 28th, 2015
235
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.68 KB | None | 0 0
  1. import java.util.Iterator;
  2. import java.util.LinkedList;
  3.  
  4.  
  5. public class findNthToLastElement {
  6.  
  7.     public static int findNth(LinkedList<Integer> list,int n){
  8.        
  9.         if (n == 0){
  10.             return 0;
  11.         }
  12.         Iterator<Integer> itr = list.iterator();
  13.         int index = list.size()+1 - n;
  14.         int num = 0;
  15.        
  16.         for (int i = 0; i < index; i++){
  17.             num = itr.next();
  18.         }
  19.         return num;
  20.     }
  21.    
  22.    
  23.     public static void main (String argv []){
  24.        
  25.         LinkedList<Integer> list = new LinkedList<Integer>();
  26.  
  27.        
  28.         list.add(1);
  29.         list.add(2);
  30.         list.add(5);
  31.         list.add(2);
  32.         list.add(5);
  33.         list.add(20);
  34.         list.add(4);
  35.         System.out.println(list);
  36.        
  37.         System.out.println(findNth(list, 7));
  38.     }
  39.    
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement