gpt4 book ai didi

java - java中链表的实现

转载 作者:行者123 更新时间:2023-11-30 06:07:42 26 4
gpt4 key购买 nike

我正在阅读有关java中的链表的内容,我确实编写了这段代码,当我运行它时,我得到3作为输出,它应该打印出插入数字的相反顺序,如下所示:10 7 3 ..我的代码有什么问题?

public class List {
private class ListNode {
private int contents;
private ListNode next;

ListNode(int contents) {
this.contents = contents;
this.next = null;
}
}

private ListNode head;

public List() {
head = null;
}

public void insert(int contents) {

ListNode newNode = new ListNode(contents);
if (head == null) {
head = newNode;
}

ListNode current = head;
while (current != null) {
current = current.next;
}

current = newNode;

}

public void reverse() {

ListNode current = head;
ListNode nodeNext = current.next;

while (nodeNext != null) {
current.next = null;
nodeNext.next = current;
current = nodeNext;
}

head = current;
}

public String toString() {

String s = "";
ListNode current = head;
while (current != null) {
s = current.contents + s;
current = current.next;
}

return s;
}

public static void main(String[] args) {

List l = new List();
l.insert(3);
l.insert(7);
l.insert(10);
l.reverse();
System.out.println(l.toString());

}
}

谢谢

最佳答案

您的 insert 方法不会将新节点连接到现有列表的最后一个节点。您必须将新节点分配给现有列表最后一个节点的 node.next :

public void insert(int contents) {

ListNode newNode = new ListNode(contents);
if (head == null) {
head = newNode;
return;
}

ListNode current = head;
while (current.next != null) {
current = current.next;
}

current.next = newNode;

}

关于java - java中链表的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40992632/

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