// CS210 - Algorithms and Data Structures I // Department of Computer Science // National University of Ireland, Maynooth // // Extra material in preparation for CS211 // Tom Naughton // December 2000 // //--------------------------------------------------------- //http://www.cs.may.ie/~tnaughton/cs210/ //========================================================= // Examples of recursive implementations of linked-list // methods that you should be familiar with. // // A print method // public void print() { /* Prints the entire list from the head. */ System.out.print("List:"); printRec(head); System.out.println(); } private void printRec(Node n) { /* Private recursive method that does all the work ** for print(). */ if (n != null) { System.out.print(n.getData().toString() + ','); printRec(n.getNext()); } } // // A method to print in reverse // public boolean contains(Object o) { /* Return true if o is in the list. */ return containsRec(head, o); } private boolean containsRec(Node n, Object o) { /* Private recirsive method that does all the work ** for contains(o). It returns true at the first ** encounter with o, and returns false if it ever ** reaches the end of the list. */ if (n == null) { return false; } else if (n.getData().equals(o)) { return true; } else { return containsRec(n.getNext(), o); } } // // A method to print in reverse // public void printInReverse() { /* Prints the entire list from the head. */ System.out.print("List:"); printInReverseRec(head); System.out.println(); } private void printInReverseRec(Node n) { /* Private recursive method that does all the work ** for printReverse(). */ if (n != null) { printRec(n.getNext()); System.out.print(n.getData().toString() + ','); } }