Source of StringLinkedList.java


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