Source of LinkedList2.java


  1: import java.util.ArrayList;

  3: public class LinkedList2<E>
  4: {
  5:     private ListNode head;

  7:     public LinkedList2( )
  8:     {
  9:         head = null;
 10:     }

 12:     public void showList( )
 13:     {
 14:         ListNode position = head;
 15:         while (position != null)
 16:         {
 17:             System.out.println(position.getData( ));
 18:             position = position.getLink( );
 19:         }
 20:     }

 22:     public int length( )
 23:     {
 24:         int count = 0;
 25:         ListNode position = head;
 26:         while (position != null)
 27:         {
 28:             count++;
 29:             position = position.getLink( );
 30:         }
 31:         return count;
 32:     }

 34:     public void addANodeToStart(E addData)
 35:     {
 36:         head = new ListNode(addData, head);
 37:     }

 39:     public void deleteHeadNode( )
 40:     {
 41:         if (head != null)
 42:         {
 43:             head = head.getLink( );
 44:         }
 45:         else
 46:         {
 47:             System.out.println("Deleting from an empty list.");
 48:             System.exit(0);
 49:         }
 50:     }

 52:     public boolean onList(E target)
 53:     {
 54:         return find(target) != null;
 55:     }

 57:     private ListNode find(E target)
 58:     {
 59:         boolean found = false;
 60:         ListNode position = head;
 61:         while (position != null)
 62:         {
 63:             E dataAtPosition = position.getData();
 64:             if (dataAtPosition.equals(target))
 65:                 found = true;
 66:             else
 67:                 position = position.getLink();
 68:         }
 69:         return position;
 70:     }

 72:     private ArrayList<E> toArrayList()
 73:     {
 74:                 ArrayList<E> list = new ArrayList<E>(length());
 75:                 ListNode position = head;
 76:                 while (position != null)
 77:                 {
 78:                         list.add(position.data);
 79:                         position = position.link;
 80:                 }
 81:                 return list;
 82:         }

 84:         private class ListNode
 85:         {
 86:                 private E data;
 87:                 private ListNode link;

 89:                 public ListNode()
 90:                 {
 91:                         link = null;
 92:                         data = null;
 93:                 }
 94:                 public ListNode(E newData, ListNode linkValue)
 95:                 {
 96:                         data = newData;
 97:                         link = linkValue;
 98:                 }
 99:                 public E getData()
100:                 {
101:                         return data;
102:                 }
103:                 public ListNode getLink()
104:                 {
105:                         return link;
106:                 }
107:         }
108: }