gpt4 book ai didi

java - 我正在用 Java 构建一个双链表,当我尝试检索任何信息时,似乎下一个和上一个节点始终为空

转载 作者:行者123 更新时间:2023-12-01 17:52:05 24 4
gpt4 key购买 nike

我已经调试了几个小时,但我看不出我的搜索方法找不到任何内容的任何原因。我的 toString 只返回第一个节点,然后又什么也不返回。有人能帮我吗?

在调试时,我可以确认列表的顺序是正确的,我可以切换 addLast 和 addFirst 并且始终返回第一个元素,但除此之外,我不知道。第一个总是在 head.info 中感到痛苦,在调试过程中我看到了这一点,但随后 prev 和 next 仍然为空。提前致谢!

public class DoubleLinkedList {

private DoubleNode head;

public DoubleLinkedList() {
head = null;
}

public class DoubleNode {
int info;
DoubleNode prev;
DoubleNode next;

public DoubleNode(int key) {
info = key;
prev = next = null;
}
}


public DoubleNode search(int key) {
DoubleNode current = this.head;

while (current != null && current.info != key) {
current = current.next;
}
return current;
}

public void addFirst(int key) {
this.head = new DoubleNode(key);
}

public void addLast(int key) {
DoubleNode node = new DoubleNode(key);
DoubleNode current;

if (head == null) {
this.head = node;
} else {
current = this.head;
while (current.next != null) {
current = current.next;
current.next = node;
node.prev = current;
}
}
}

public int delete(int key) {
DoubleNode current, sent;
current = search( key );
if (current != null) {
sent = delete( current );
return sent.info;
} else {
return -1;
}
}

private DoubleNode delete(DoubleNode node) {
if (node.prev != null) {
(node.prev).next = node.next;
} else {
this.head = node.next;
}
if (node.next != null) {
(node.next).prev = node.prev;
}
return node;
}

public String toString() {
String string = "";
while (head != null) {
string += head.info + " ";
head = head.next;
}
return string;
}

public static void main(String[] args) {
DoubleLinkedList test = new DoubleLinkedList();
test.addLast( 3 );
test.addLast( 5 );
test.addFirst( 7 );
System.out.println(test);
System.out.println( "Search: " + test.search( 1 ) );
}
}

结果如下:

7,
Search: null

最佳答案

您的 addFirst 方法当前未设置新头的 next 属性。它需要更像这样:

public void addFirst(int key) {
DoubleNode node = new DoubleNode(key);
node.next = this.head;
this.head = node;
}

关于java - 我正在用 Java 构建一个双链表,当我尝试检索任何信息时,似乎下一个和上一个节点始终为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60779427/

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