// SortedList.java // implementation // public class SortedList { private int length; private ListNode head; private ListNode currentPos; public SortedList() { length = 0; head = null; currentPos = null; } public boolean isEmpty() { return length==0; } public void insert(String item) { ListNode newNode, preLoc, location; length ++; boolean moreToSearch; location = head; preLoc = null; moreToSearch = (location != null); while(moreToSearch) { if(item.compareToIgnoreCase(location.getData())>0) { preLoc = location; location = location.getLink(); moreToSearch = (location != null); } else moreToSearch = false; } newNode = new ListNode(item, null); // insert as the first node if(preLoc == null) { newNode.setLink(head); head = newNode; } else { newNode.setLink(location); preLoc.setLink(newNode); } currentPos = newNode; } public void remove(String item) { ListNode location = head; // temp pointer // for the first node if(location.getData().equalsIgnoreCase(item)) head = head.getLink(); else // not the first one { while(!location.getLink().getData().equalsIgnoreCase(item)) location = location.getLink(); ListNode temp = location.getLink(); // the current node points the node that // temp's next points to location.setLink(temp.getLink()); } length --; } public void Print() { recursivePrint(head); System.out.println(); //printFrom(head); } private void recursivePrint(ListNode ptr) { if(ptr!=null) { System.out.print(ptr.getData() + " "); recursivePrint(ptr.getLink()); } } public void printFrom(ListNode temp) { System.out.println("The list is: "); while(temp != null) { System.out.print(temp.getData() + " "); temp = temp.getLink(); } System.out.println(); } private void reversePrint(ListNode ptr) { if(ptr!=null) { reversePrint(ptr.getLink()); System.out.print(ptr.getData() + " "); } } public void revPrint() { reversePrint(head); System.out.println(); } public String getCurentItem() { return currentPos.getData(); } public String getNextItem() { ListNode temp = currentPos; temp = temp.getLink(); return temp.getData(); } public String getCurrentItem() { return currentPos.getData(); } public boolean search(String item) { boolean find = false; ListNode temp = head; while(temp != null) { if(temp.getData().equalsIgnoreCase(item)) { find = true; currentPos = temp; } // move one node forward temp = temp.getLink(); } return find; } } /* public void deleteItem(String item); public static void main(String[] args) { SortedList sl = new SortedList(); sl.insert("Yon"); sl.revPrint(); sl.insert("Lee"); sl.revPrint(); sl.insert("Tom"); sl.revPrint(); if(sl.search("Tom")) { System.out.println("We got it."); sl.remove("Tom"); } else System.out.println("The code has error."); sl.revPrint(); } } */