/**
* Nodes for a singly-linked list.
*/
public class Node {
/** The value in the current node. A value of null
* indicates (...)
*/
protected Object value;
/** The next node in the list. A value of null
* indicates that this is the last element of the list.
*/
protected Node next;
...
} // Node
tail, which now needs to create new list
objects.
/**
* A singly-linked list.
*/
public class List {
/** The elements of the list, starting at the front */
protected Node front;
/** The last element of the list. */
protected Node back;
/** The current element of the list. */
protected Node current;
...
} // List
/**
* Return the first element in a list.
* pre: The list is nonempty.
* post: The first element is returned.
*/
public Object head() {
return value;
} // head
/**
* Return all but the first element in the lsit.
* pre: The list is nonempty.
* post: The list containing all but the first element is
* returned.
* post: The two lists share nodes, so modifications to one
* may affect the other.
*/
public Node tail() {
return next;
} // head
head is also
relatively straightforward
/**
* Return the first element in a list.
* pre: The list is nonempty.
* post: The first element is returned.
*/
public Object head() throws ListException {
// Sanity check
if (front == null) {
throw new ListException("Can't take the head of an empty list.");
}
else {
return front.head();
}
} // head
tail is much more complicated, as it
requires us to build a new structure, and to consider the implications
of combining tail with other operations on the returned
list. (This is likely why our book doesn't provide a tail
operation.)
/**
* Return all but the first element in the lsit.
* pre: The list is nonempty.
* post: The list containing all but the first element is
* returned.
* post: The two lists do not share nodes, so they may
* be modified independently.
* post: The current element of the new list is the first
* element of that list.
*/
public List tail() throws ListException {
// Sanity check
if (front == null) {
throw new ListException("Can't take the tail of an empty list.");
}
// Standard implementation
else {
// Make a new list
List my_tail = new List();
my_tail.front = front.next().clone();
my_tail.back = figureOutWhereTheBackIs();
my_tail.current = my_tail.front; // As good as anywhere else
}
} // tail
Disclaimer Often, these pages were created "on the fly" with little, if any, proofreading. Any or all of the information on the pages may be incorrect. Please contact me if you notice errors.
Source text last modified Mon Oct 13 10:04:16 1997.
This page generated on Wed Nov 5 12:38:34 1997 by SiteWeaver.
Contact our webmaster at rebelsky@math.grin.edu