Would anyone be able to help me write a removeFirstOccurrence method for this doubly linked list?
It removes the node having the first occurrence of the target data. The search starts at the head. If the target data is not in the list, then the list remains unchanged. The next field of the last node has value null. There is no tail reference.
public class DoublyLinkedList {
protected Node head; // Note there is no tail reference.
public void addToFront(String data) {
head = new Node(data, head, null);
if(head.next != null) {
head.next.previous = head;
}
public void removeFirstOccurrence(String data) {
}
protected class Node {
protected String data;
protected Node next;
protected Node previous;
private Node(String data, Node next, Node previous) {
this.data = data;
this.next = next;
this.previous = previous;
}
private Node(String data) {
this(data, null, null);
}
} // end of Node class
} // end of DoublyLinkedList class
so far I wrote something like this but I am getting a null pointer exception when removing a string that isn't on the list. I have marked where the NPE occurs. if you can help figure out why or if you have a completely different method that works thats OK too just let me know, thanks!
public void removeFirstOccurance(String data) {
if (data.equals(null)) {
throw new java.lang.IllegalArgumentException("Data is null");
}
if (head == null) {
throw new java.util.NoSuchElementException("List is empty");
}
Node current = head;
if (current.data.equals(data)) {
head = current.next;
} else {
boolean found = false; //keeps track if we found the element
while (current != null && !found) {
if (current.next.previous == null) { //NPE here
current.next.previous = current;
}
current = current.next;
if (current.data.equals(data)) {
found = true;
if (current.next == null) {
current.previous.next = null;
} else {
current.previous.next = current.next;
}
}
}
}
}