//------------------------------------------------------------------------- // RefSortedList.java by Dale/Joyce/Weems Chapter 6 // // Implements the ListInterface using a linked list. It is kept in increasing // order as defined by the compareTo method of the added elements. Only // Comparable elements may be added to a list. // // Null elements are not permitted on a list. // // One constructor is provided, one that creates an empty list. //---------------------------------------------------------------------------- package ch06.lists; import support.LLNode; public class RefSortedList> extends RefUnsortedList implements ListInterface { public RefSortedList() { super(); } public void add(T element) // Adds element to this list. { LLNode prevLoc; // trailing reference LLNode location; // traveling reference T listElement; // current list element being compared // Set up search for insertion point. location = list; prevLoc = null; // Find insertion point. while (location != null) { listElement = location.getInfo(); if (listElement.compareTo(element) < 0) // list element < add element { prevLoc = location; location = location.getLink(); } else break; } // Prepare node for insertion. LLNode newNode = new LLNode(element); // Insert node into list. if (prevLoc == null) { // Insert as first node. newNode.setLink(list); list = newNode; } else { // Insert elsewhere. newNode.setLink(location); prevLoc.setLink(newNode); } numElements++; } }