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:      Returns the number of nodes in the list.
 14:     */
 15:     public int length( )
 16:     {
 17:         int count = 0;
 18:         ListNode position = head;
 19:         while (position != null)
 20:         {
 21:             count++;
 22:             position = position.getLink( );
 23:         }
 24:         return count;
 25:     }
 26:     
 27:     /**
 28:      Adds a node at the start of the list. The added node has addData
 29:      as its data. The added node will be the first node in the list.
 30:     */
 31:     public void addANodeToStart(String addData)
 32:     {
 33:         head = new ListNode(addData, head);
 34:     }
 35:     
 36:     public void deleteHeadNode( )
 37:     {
 38:         if (head != null)
 39:         {
 40:             head = head.getLink( );
 41:         }
 42:         else
 43:         {
 44:             System.out.println("Deleting from an empty list.");
 45:             System.exit(0);
 46:         }
 47:     }
 48: 
 49:     public boolean onList(String target)
 50:     {
 51:         return (Find(target) != null);
 52:     }
 53:     
 54:     /**
 55:      Finds the first node containing the target data and 
 56:      returns a reference to that node. 
 57:      If target is not in the list, null is returned.
 58:     */
 59:     private ListNode Find(String target)
 60:     {
 61:         ListNode position;
 62:         position = head;
 63:         String dataAtPosition;
 64:         while (position != null)
 65:         {
 66:             dataAtPosition = position.getData( );
 67:             if (dataAtPosition.equals(target))
 68:                 return position;
 69:             position = position.getLink( );
 70:         }
 71:         //target was not found
 72:         return null; 
 73:     }
 74:     
 75:     public void showList( )
 76:     {
 77:         ListNode position;
 78:         position = head;
 79:         while (position != null)
 80:         {
 81:             System.out.println(position.getData( ));
 82:             position = position.getLink( );
 83:         }
 84:     }
 85: }