// file IntList.java // Recursive functions over linked list of ints. // // Linked list of int. No header, empty lists not permitted. public class IntList { private int value; private IntList next; public IntList(int v, IntList n) { // Constructor value = v; next = n; } public int getValue() { return value; } // Getters public IntList getNext() { return next; } public void setValue(int v) { value = v; } // Setters public void setNext(IntList n) { next = n; } // Find the last node of a linked list. public IntList findLast() { if (getNext() == null) return this; else return getNext().findLast(); } // Add a new node with value v at the end of l; public void addEnd(int v) { findLast().setNext(new IntList(v,null)); } // Add up the values in a list, recurring down the owner public int sumList() { if (getNext() == null) return getValue(); else return getValue() + getNext().sumList(); } // Convert list of int to string // Recursive method for constructing the end of the string, after the // initial open bracket. public String toString1() { if (getNext() == null) return getValue() + "]"; else return getValue() + ", " + getNext().toString1(); } // Top level rountine that starts with the "[" and then calls toString1 to // do the rest. public String toString() { return "[" + toString1(); } // Recursive method for finding the sum of a list, using recursion down // an argument. Note that this is a static method, associated with the class // not with an object owner. static public int sumListArg(IntList l) { if (l==null) return 0; else return l.getValue() + sumListArg(l.getNext()); } static public void main(String[] args) { IntList l = new IntList(2,null); l.addEnd(3); l.addEnd(5); l.addEnd(7); System.out.println(l.toString()); System.out.println("Sum = " + l.sumList()); } // end main } // end RecursiveIntList