//************************************************* // // An example of linked lists, initially for lists of // integers. We define the class and appropriate methods // //************************************************** public class IntList { private IntNode head; public IntList(){ head = null; } public boolean isEmpty(){return head == null;} public String toString(){ if (isEmpty()) return "()"; else return "(" + head + ")"; } public void add(int data){ head = new IntNode(data,head); } public void delete(int e){head = delete(head,e);} private IntNode delete(IntNode x, int e) { if (x == null) return null; else if (x.getData() == e) return delete(x.getNext(),e); else { x.setNext(delete(x.getNext(),e)); return x; } } public int size(){ int size =0; IntNode nodeHopper = head; while (nodeHopper != null){ nodeHopper = nodeHopper.getNext(); size++; } return size; } // // return the number of elements in the list // zero if empty // public int sum(){ int sum = 0; IntNode nodeHopper = head; while (nodeHopper != null){ sum = sum + nodeHopper.getData(); nodeHopper = nodeHopper.getNext(); } return sum; } // // return the sum of the data in the list // zero if empty // public int max() throws IntListException { if (isEmpty()) throw new IntListException("max of empty list!"); else { IntNode nodeHopper = head; int max = -9999, x = 0; while (nodeHopper != null){ x = nodeHopper.getData(); if (x>max) max = x; nodeHopper = nodeHopper.getNext(); } return max; } } // // return the largest data in the list. // throw a IntListException if empty // public boolean isPresent(int e) {return isPresent(head,e);} private boolean isPresent(IntNode x, int e){ return (x != null) && ((x.getData() == e) || isPresent(x.getNext(),e)); } public void show(){ System.out.println(this + " isEmpty()=" + isEmpty() + " size()=" + size() + " sum()=" + sum() + " max()=" + max()); } public static void main(String[] args) throws Exception { IntList L1 = new IntList(); System.out.println(L1.isEmpty() + " " + L1); L1.add(2); System.out.println(L1.isEmpty() + " " + L1); L1.add(1); System.out.println(L1.isEmpty() + " " + L1); IntList L2 = new IntList(); for (int i=10;i>0;i--) L2.add(i); System.out.println(L2.isEmpty() + " " + L2); for (int i=10;i>0;i--) L2.add(i); L2.delete(50); System.out.println(L2.isEmpty() + " " + L2); L1.delete(1); System.out.println(L1.isEmpty() + " " + L1); L1.delete(2); System.out.println(L1.isEmpty() + " " + L1); L2.show(); L1.show(); System.out.println(L2.max()); } }