// Doubly linked list
// Written by Elena Machkasova, Oct. 6 2004
// Modified Feb. 23 2005
public class DoubleLinkedList {
private DoubleNode first;
private DoubleNode last;
public DoubleLinkedList() {
// sets 'first' and 'last' to null
}
public boolean isEmpty() {
return (first == null);
}
public DoubleNode getFirst() {
return first;
}
public DoubleNode getLast() {
return last;
}
// works for non-null parameters only
// if a null parameter is passed, it will print error message and exit
public void addFront(DoubleNode n) {
if (n == null) {
System.out.println("addFront: received a null parameter");
System.exit(0);
}
n.setNext(first);
// check if this is the only element on the list
// if not, set the 'prev' of the first
// if it is, set 'last'
if (first != null) {
first.setPrev(n);
} else {
last = n;
}
first = n;
}
// works for non-null parameters only
// if a null parameter is passed, it will print error message and exit
public void addBack(DoubleNode n) {
if (n == null) {
System.out.println("addBack: received a null parameter");
System.exit(0);
}
n.setPrev(last);
// if this is not the only node, reset the reference
// from the previous node
// Otherwise reset first
if (last != null) {
last.setNext(n);
} else {
first = n;
}
last = n;
}
// removes the element. If there is no element to remove,
// prints an error message and exits
public void removeFront() {
if (first == null) {
System.out.println("removeFront: can't remove from an empty list");
System.exit(0);
}
// if there is only one element
if (first == last) {
first = null;
last = null;
} else {
// the second-to-first is now first:
first.getNext().setPrev(null);
first = first.getNext();
}
}
public void removeBack() {
if (last == null) {
System.out.println("removeBack: can't remove from an empty list");
System.exit(0);
}
// if there is only one element
if (first == last) {
first = null;
last = null;
} else {
// the second-to-first is now first:
last.getPrev().setNext(null);
last = last.getPrev();
}
}
}