// List.java
// Class ListNode and class List definitions
// class to represent one node in a list
class ListNode {
// package access members; List can access these directly
Object data;
ListNode nextNode;
// constructor to create a ListNode that refers to object
ListNode( Object object )
{
this( object,null );
}
// constructor to create ListNode that refers to Object
// and to next ListNode in List
ListNode( Object object,ListNode node )
{
data = object;
nextNode = node;
}
// return Object in this node
Object getObject()
{
return data;
}
// get next node
ListNode getNext()
{
return nextNode;
}
} // end class ListNode
// class List definition
public class List {
private ListNode firstNode;
private ListNode lastNode;
private String name; // String like "list" used in printing
// construct an empty List with a name
public List( String string )
{
name = string;
firstNode = lastNode = null;
}
// construct empty List with "list" as the name
public List()
{
this( "list" );
}
// Insert Object at front of List,If List is empty,
// firstNode and lastNode will refer to same object.
// Otherwise,firstNode refers to new node.
public synchronized void insertAtFront( Object insertItem )
{
if ( isEmpty() )
firstNode = lastNode = new ListNode( insertItem );
else
firstNode = new ListNode( insertItem,firstNode );
}
// Insert Object at end of List,If List is empty,
// firstNode and lastNode will refer to same Object.
// Otherwise,lastNode's nextNode refers to new node.
public synchronized void insertAtBack( Object insertItem )
{
if ( isEmpty() )
firstNode = lastNode = new ListNode( insertItem );
else
lastNode = lastNode.nextNode =
new ListNode( insertItem );
}
// remove first node from List
else
firstNode = firstNode.nextNode;
// return removed node data
return removeItem;
}
// Remove last node from List
public synchronized Object removeFromBack()
throws EmptyListException
{
Object removeItem = null;
// throw exception if List is empty
115 if ( isEmpty() )
116 throw new EmptyListException( name );
117
118 // retrieve data being removed
119 removeItem = lastNode.data;
120
121 // reset firstNode and lastNode references
122 if ( firstNode == lastNode )
123 firstNode = lastNode = null;
124
125 else {
126
127 // locate new last node
128 ListNode current = firstNode;
129
130 // loop while current node does not refer to lastNode
131 while ( current.nextNode != lastNode )
132 current = current.nextNode;
133
85 public synchronized Object removeFromFront()
86 throws EmptyListException
87 {
88 Object removeItem = null;
89
90 // throw exception if List is empty
91 if ( isEmpty() )
92 throw new EmptyListException( name );
93
94 // retrieve data being removed
95 removeItem = firstNode.data;
96
97 // reset the firstNode and lastNode references
98 if ( firstNode == lastNode )
99 firstNode = lastNode = null;
100