// // P.127 // A string linked list class, based on the string list node class // class LinkedList { private ListNode head; public LinkedList() { head = null; } public void insert(String addData) { head = new ListNode(addData, head); } public void print() // p.127 showList { ListNode position = head; while(position!= null) { System.out.print(position.getData() + " "); position = position.getLink(); } System.out.println(); } public void delete() // p.128 deleteHeadNode { if(head!=null) head = head.getLink(); } public int length() { int count = 0; ListNode position = head; while(position!=null) { count ++; position = position.getLink(); } return count; } public boolean onList(String target) { return find(target)!=null; } private ListNode find(String target) { boolean found=false; ListNode position=head; while(position!=null && !found) { String dataAtPosition = position.getData(); if(dataAtPosition.equals(target)) found = true; else position=position.getLink(); } return position; } public static void main(String[] args) { LinkedList me = new LinkedList(); me.insert("ODU"); me.insert("VWC"); me.insert("UVA"); me.print(); me.delete(); me.print(); System.out.println("length = " + me.length()); // Q: find "VWC" if it is on the list? if(me.onList("VWC")) System.out.println("VWC is on the list."); else System.out.println("VWC is not on the list"); me.insert("Harvard"); System.out.println("length = " + me.length()); System.out.println("\n\nDone.\n\n"); } }