我试图更好地告诉老师关于如何从双向链表中删除节点的说明,她在电路板上的内容是
public void deleteNode(Node D){
Node current = head;
while(current.data != D.data && current.next != null){
current = current.next;
}
d.prev.next = d.next;
d.next.prev = current.prev.
}
我无法帮助,但觉得这还不足以删除节点。我在想也许她的意思
current.prev.next = d.next and
current.next.prev = d.prev
一旦我弄清楚如何更好地理解这一点,如果我想从中间删除一个节点
就有意义了public void deleteMiddle(){
Node current = head;
int i = 0;
while(i < size/2){
current = current.next;
i++;
}
deleteNode(current);
}
答案 0 :(得分:1)
正确的方法是传入值,即data
,或者使方法保密,以防止滥用。
或两者兼顾:
public void deleteNode(int data) {
Node current = head;
while (current != null && current.data != data) {
current = current.next;
}
deleteNode(current);
// Note: We silently do nothing if 'data' not found
}
private void deleteNode(Node node) {
if (node != null) {
// Here we can rely on 'node' actually being in our list
if (node.prev != null)
node.prev.next = node.next;
else
head = node.next;
if (node.next != null)
node.next.prev = node.prev;
else
tail = node.prev;
}
}