Source of StringLinkedList.java


  1: //StringLinkedList.java
  2: 
  3: public class StringLinkedList
  4: {
  5:     private ListNode head;
  6:     
  7:     public StringLinkedList()
  8:     {
  9:         head = null;
 10:     }
 11:     
 12:     /**
 13:      Displays the data on the list.
 14:     */
 15:     public void showList()
 16:     {
 17:         ListNode position = head;
 18:         while (position != null)
 19:         {
 20:             System.out.println(position.getData());
 21:             position = position.getLink();
 22:         }
 23:     }
 24:     
 25:     /**
 26:      Returns the number of nodes on the list.
 27:     */
 28:     public int length()
 29:     {
 30:         int count = 0;
 31:         ListNode position = head;
 32:         while (position != null)
 33:         {
 34:             count++;
 35:             position = position.getLink();
 36:         }
 37:         return count;
 38:     }
 39:     
 40:     /**
 41:      Adds a node containing the data addData at the 
 42:      start of the list.
 43:         */
 44:     public void addANodeToStart(String addData)
 45:     {
 46:         head = new ListNode(addData, head);
 47:     }
 48:     
 49:     /**
 50:      Deletes the first node on the list.
 51:     */
 52:     public void deleteHeadNode()
 53:     {
 54:         if (head != null)
 55:         {
 56:             head = head.getLink();
 57:         }
 58:         else
 59:         {
 60:             System.out.println("Deleting from an empty list.");
 61:             System.exit(0);
 62:         }
 63:     }
 64: 
 65:     /**
 66:      Sees whether target is on the list.
 67:     */
 68:     public boolean onList(String target)
 69:     {
 70:         return find(target) != null;
 71:     }
 72:     
 73:     // Returns a reference to the first node containing the
 74:     // target data. If target is not on the list, returns null.
 75:         private ListNode find(String target)
 76:     {
 77:                 boolean found = false;
 78:         ListNode position = head;
 79:         while ((position != null) && !found)
 80:         {
 81:             String dataAtPosition = position.getData();
 82:             if (dataAtPosition.equals(target))
 83:                                 found = true;
 84:                         else
 85:                                 position = position.getLink();
 86:         }
 87: 
 88:         return position;
 89:     }
 90: }