Programming Homework Help
Insert & Delete Methods Java Coding Task
Insert & Delete Methods
public void insertNode(T insertItem){
boolean found;
DoubleLinkedListNode<T> current;//moving reference
DoubleLinkedListNode<T> trailCurrent = null; //just before current
// Set up node to be inserted
DoubleLinkedListNode<T> newNode = new DoubleLinkedListNode<T>();
newNode.info = insertItem;
newNode.next = null;
newNode.back = null;
//if the list is empty, newNode is the only node
if (first == null) {
first = newNode;
last = newNode;
count++;
}
else {
found = false;
current = first;
//search the list
while (current != null && !found) {
Comparable<T> temp = (Comparable<T>) current.info;
if (temp.compareTo(insertItem) >= 0)
found = true;
else {
trailCurrent = current;
current = current.next;
}
}
//insert new node before first
if (current == first) {
first.back = newNode;
newNode.next = first;
first = newNode;
count++;
}
else {
//insert newNode between trailCurrent and current
if (current != null) {
trailCurrent.next = newNode;
newNode.back = trailCurrent;
newNode.next = current;
current.back = newNode;
}
else {
//insert new node after last
trailCurrent.next = newNode;
newNode.back = trailCurrent;
last = newNode;
}
count++;
}
}
}
public void deleteNode(T deleteItem) {
DoubleLinkedListNode<T> current; //moving reference
DoubleLinkedListNode<T> trailCurrent;//just before current
boolean found;
if (first == null)
System.err.println("Cannot delete from an empty list.");
//if node to be deleted is the first node
else if (first.info.equals(deleteItem)) {
current = first;
first = first.next;
if (first != null)
first.back = null;
else
last = null;
count--;
}
else {
found = false;
current = first;
//search the list
while (current != null && !found) {
Comparable<T> temp = (Comparable<T>) current.info;
if (temp.compareTo(deleteItem) >= 0)
found = true;
else
current = current.next;
}
if (current == null)
System.out.println("The item to be deleted is not in the list.");
else if (current.info.equals(deleteItem)) {
trailCurrent = current.back;
trailCurrent.next = current.next;
if (current.next != null)
current.next.back = trailCurrent;
if (current == last)
last = trailCurrent;
count--;
}
else
System.out.println("The item to be deleted is not in list.");
}
}