【发布时间】:2015-02-02 01:12:49
【问题描述】:
谁能帮我为这个双向链表写一个 removeFirstOccurrence 方法?
它删除第一次出现目标数据的节点。搜索从头部开始。如果目标数据不在列表中,则列表保持不变。最后一个节点的下一个字段的值为 null。没有尾部参考。
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
到目前为止,我写了类似这样的东西,但是在删除不在列表中的字符串时出现空指针异常。我已经标记了 NPE 发生的位置。如果您可以帮助找出原因,或者如果您有完全不同的方法也可以,请告诉我,谢谢!
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;
}
}
}
}
}
【问题讨论】:
标签: java linked-list