deleteCurrent and deleteLast.
previous
link to each Node, so that you can move both backwards
and forwards along the list.
Node
class, you generally want to use doubly-linked lists only with
a wrapper class.)
Node class.
/**
* Delete the current node from a sequence of nodes.
* pre: This node is defined/initialized
* post: This node is no longer referred to by the previous and
* next nodes.
*/
public void deleteMe() {
if (previous != null) {
previous.next = next;
} // if there is a previous element
if (next != null) {
next.previous = previous;
} // if there is a next element
} // deleteMe
List class. You can
fill in appropriate pre- and post-conditions.
public Object deleteCurrent() throws ListException {
if (current == null) {
throw new ListException("Can't determine current element");
}
else if (front == null) {
throw new ListException("Can't delete elements from empty list");
}
else {
Node deleted = current;
current.deleteMe();
if (current.nextElement() == null)
current = front;
else
current = current.nextElement();
return deleted.contents();
}
} // deleteCurrent
public Object deleteLast() throws ListException {
if (front == null) {
throw new ListException("Can't delete elements from empty list");
}
else {
Node deleted = back;
back.deleteMe();
back= back.previous;
return deleted.contents();
}
} // deleteLast
public Object deleteCopies(Object element) {
// Delete all copies by stepping through the list
for(Node pointer = front;
pointer != null;
pointer = pointer.nextElement()) {
if (pointer.contents().equals(element)) {
pointer.deleteMe();
}
} // for
// Update current and back if necessary
if (current.contents().equals(element)) current = front;
if (back.contents().equals(element)) computeBack();
} // deleteCopies
deleteLast now takes constant time, rather than
time linear in the size of the structure.
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 Wed Oct 15 10:29:00 1997.
This page generated on Wed Nov 5 12:38:32 1997 by SiteWeaver.
Contact our webmaster at rebelsky@math.grin.edu