Source of LinkedList.java


  1: //LinkedList.java
  2: 
  3: import java.io.*;
  4: 
  5: public class LinkedList implements Serializable
  6: {
  7:   //Default constructor - creates an empty list
  8:   public LinkedList() {}
  9: 
 10:   //Constructor to create a list containing one object
 11:   public LinkedList(Object item)
 12:   {
 13:     if(item != null)
 14:       current = end = start = new ListItem(item);
 15:       //item is the start and end
 16:   }
 17: 
 18:   //Construct a linked list from an array of objects
 19:   public LinkedList(Object[] items)
 20:   {
 21:     if(items != null)
 22:     {
 23:       //Add the items to the list
 24:       for(int i = 0; i < items.length; i++)
 25:         addItem(items[i]);
 26:       current = start;
 27:     }
 28:   }
 29: 
 30:   //Add an item object to the list
 31:   public void addItem(Object item)
 32:   {
 33:     ListItem newEnd = new ListItem(item); //Create a new ListItem
 34:     if(start == null)                     //Is the list empty?
 35:       start = end = newEnd;     //Yes, so new element is start and end
 36:     else
 37:     {                           //No, so append new element
 38:       end.next = newEnd;        //Set next variable for old end
 39:       end = newEnd;             //Store new item as end
 40:     }
 41:   }
 42: 
 43:   //Get the first object in the list
 44:   public Object getFirst()
 45:   {
 46:     current = start;
 47:     return start == null ? null : start.item;
 48:   }
 49: 
 50:   //Get the next object in the list
 51:   public Object getNext()
 52:   {
 53:     if(current != null)
 54:       current = current.next; //Get the reference to the next item
 55:     return current == null ? null : current.item;
 56:   }
 57: 
 58:   private ListItem start = null;   //First ListIem in the list
 59:   private ListItem end = null;     //Last ListIem in the list
 60:   private ListItem current = null; //The current item for iterating
 61: 
 62:   private class ListItem implements Serializable
 63:   {
 64:     //Constructor
 65:     public ListItem(Object item)
 66:     {
 67:       this.item = item;  //Store the item
 68:       next = null;       //Set next as end point
 69:     }
 70: 
 71:     //Return class name & object
 72:     public String toString()
 73:     {
 74:       return "ListItem " + item ;
 75:     }
 76: 
 77:     ListItem next; //Refers to next item in the list
 78:     Object item;
 79:   }
 80: }