gpt4 book ai didi

java - 从双向链表中删除 - java

转载 作者:行者123 更新时间:2023-12-02 11:24:42 25 4
gpt4 key购买 nike

我试图更好地理解我的老师关于如何从双向链表中删除节点的笔记,她在板上的内容是

 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);
}

最佳答案

正确的方法是传入值,即数据,或者将方法设为私有(private),以防止滥用。

或者两者都做:

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;
}
}

关于java - 从双向链表中删除 - java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49700276/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com