// Computer Science Example
// List with access to front and rear only

/* The class, ListClass, has methods to add nodes to the front and rear of the list and to display the contents of the list.
    These are stored with the Node class in the package, list. */

package list;

// This interface defines the public methods in ListClass.
interface ListInterface
{
     public void addToFront (Node front);
     public void addToRear (Node rear);
     public void displayList ();
} // interface ListInterface

public class ListClass implements ListInterface
{
    private Node listHead;

    public ListClass ()
    {
        listHead = null;
    } // constructor

    // Method to add a node to the front of the list.
    public void addToFront (Node front)
    {
        if (listHead == null) listHead = front;
        else
        {
            front.setNext (listHead);
            listHead = front;
        }
    } // method addToFront

    // Method to add a node to the end of the list.
    public void addToRear (Node rear)
    {
        if (listHead == null) listHead = rear;
        else // Find the end of the list.
        {
            Node previous = listHead, current = listHead;
            while (current != null)
            {
                previous = current;
                current = current.getNext ();
            }
            previous.setNext (rear);
        }
    } // method addToRear

    // Method to display the id’s in the list.
    public void displayList ()
    {
        Node tempNode = listHead;
        while (tempNode != null)
        {
            System.out.println ("ID: " + tempNode.getId ());
            tempNode = tempNode.getNext ();
        }
    } // method displayList
} // class ListClass
 

// The Node class defines a node with an id and a next field.

package list;

public class Node
{
    private String id;
    private Node next;

    public Node (String id)
    {
        this.id = id;
        next = null;
    } // constructor

    public String getId ()
    {
        return id;
    } // method getId

    protected Node getNext ()
    {
        return next;
    } // method getNext

    protected void setNext (Node nextNode)
    {
        next = nextNode;
    } // method setNext
} // class Node
 
import list.ListClass;
import list.Node;

/* TestList is used to test the methods in the package, list. */

public class TestList
{
    public static void main (String [] args)
    {
        ListClass list = new ListClass ();
        for (int count = 0; count < 5; count ++)
        {
            Node newFront = new Node ("" + count);
            list.addToFront (newFront);
            Node newRear = new Node ("" + count);
            list.addToRear (newRear);
        }
        list.displayList ();
    } // method main
} // class TestList