korobushk

IntList

Mar 30th, 2021 (edited)
526
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.01 KB | None | 0 0
  1. public class Application {
  2.  
  3.     public static void main(String[] args) {
  4.         IntList L = new IntList(5, null);
  5.         L.rest = new IntList(10, null);
  6.         L.rest.rest = new IntList(15, null);
  7.    
  8.        
  9.         System.out.println(L.get(2));
  10.        
  11.         System.out.println(L.getRecursive(2));
  12.     }
  13.  
  14. }
  15. public class IntList {
  16.     public int first;
  17.     public IntList rest;
  18.  
  19.     public IntList(int f, IntList r) {
  20.         first = f;
  21.         rest = r;
  22.     }
  23.  
  24.     public int size() {
  25.         if (rest == null) {
  26.             return 1;
  27.         }
  28.         return 1 + this.rest.size();
  29.     }
  30.  
  31.     public int iterativeSize() {
  32.         IntList p = this;
  33.         int totalSize = 0;
  34.         while (p != null) {
  35.             totalSize += 1;
  36.             p = p.rest;
  37.         }
  38.         return totalSize;
  39.     }
  40.  
  41.     public int get(int i) {
  42.         IntList p = this;
  43.         int listS = 0;
  44.        
  45.         if(i==0) {
  46.             return first;
  47.         }
  48.         while (p != null) {
  49.             listS++;
  50.             p=p.rest;
  51.             if(listS==i) {
  52.                 return p.first ;
  53.             }
  54.            
  55.         }
  56.  
  57.         return 0;
  58.     }
  59.    
  60.     public int getRecursive(int i ) {
  61.         if(i==0) {
  62.             return first;
  63.         }
  64.         return rest.getRecursive(i-1);
  65.     }
  66.    
Add Comment
Please, Sign In to add comment