/** Return the size of the list using... recursion! */ publicintsize() { if (rest == null) { return1; } return1 + this.rest.size(); }
/** Return the size of the list using no recursion! */ publicintiterativeSize() { IntListp=this; inttotalSize=0; while (p != null) { totalSize += 1; p = p.rest; } return totalSize; }
/** Returns the ith item of this IntList. */ publicintget(int i) { if (i == 0) { return first; } return rest.get(i - 1); }
/** Method to return a string representation of an IntList */ public String toString() { if (rest == null) { // Converts an Integer to a String! return String.valueOf(first); } else { return first + " -> " + rest.toString(); } }
/** * Method to create an IntList from an argument list. * You don't have to understand this code. We have it here * because it's convenient with testing. It's used like this: * * IntList myList = IntList.of(1, 2, 3, 4, 5); * will create an IntList 1 -> 2 -> 3 -> 4 -> 5 -> null. * * You can pass in any number of arguments to IntList.of and it will work: * IntList mySmallerList = IntList.of(1, 4, 9); */ publicstatic IntList of(int ...argList) { if (argList.length == 0) returnnull; int[] restList = newint[argList.length - 1]; System.arraycopy(argList, 1, restList, 0, argList.length - 1); returnnewIntList(argList[0], IntList.of(restList)); } }