// IntList.java // // CS 101 Class Example // // Linked lists of integers. // To run this code, use "java IntList" public class IntList { // Instance variables private int head; private IntList tail; // Constructor method: public IntList(int head, IntList tail) { this.head = head; this.tail = tail; } public IntList prepend(int n) { return new IntList(n, this); } public int head() { return head; } public IntList tail() { return tail; } // ---------------------------------------------------------- // static methods that operate on IntLists public static int length(IntList L) { // return length of L if (L == null) { return 0; } else { return 1 + length(L.tail()); } } public static int sum(IntList L) { // return sum of all elements of L if (L == null) { return 0; } else { return L.head() + sum(L.tail()); } } public static int nth(int n, IntList L) { // return n-th number in L (starting with 0) if (n == 0) { return L.head(); } else { return nth(n-1, L.tail()); } } // ---------------------------------------------------------- // toString methods so we can print IntLists public String toString() { // create a string representation of this StringBuffer sb = new StringBuffer(); sb.append("["); sb.append(head); IntList toDo = tail; while (toDo != null) { sb.append(", "); sb.append(toDo.head); toDo = toDo.tail; } sb.append("]"); return sb.toString(); } // ---------------------------------------------------------- // main method for testing: public static void main(String[] argv) { IntList x = new IntList(3, new IntList(5, null)); System.out.println("x = " + x); x = x.prepend(30); System.out.println("x = " + x); IntList y = new IntList(-6, new IntList(-7, x)); System.out.println("y = " + y); System.out.println("length(x) = " + length(x)); System.out.println("length(y) = " + length(y)); System.out.println("sum(x) = " + sum(x)); System.out.println("sum(y) = " + sum(y)); System.out.println("nth(0, x) = " + nth(0, x)); System.out.println("nth(1, y) = " + nth(1, y)); System.out.println("nth(4, y) = " + nth(4, y)); } } /* Output produced: x = [3, 5] x = [30, 3, 5] y = [-6, -7, 30, 3, 5] length(x) = 3 length(y) = 5 sum(x) = 38 sum(y) = 25 nth(0, x) = 30 nth(1, y) = -7 nth(4, y) = 5 */