gpt4 book ai didi

java - 链接列表,未正确添加值

转载 作者:行者123 更新时间:2023-12-02 07:08:33 24 4
gpt4 key购买 nike

我目前正在完成我的作业,即实现 LinkedList 数据结构,我已完成所有代码,除了它无法正常工作,我正在测试它的输入代码是“1,2,3 ,4,5",但是仅输出“1”而不是所有值。

这是我的代码:

// Main Method Functions
private static LinkedList createLinkedList(int[] values) {
LinkedList list;

list = new LinkedList();
for (int i = 0; i < values.length; i++) {
list.add(values[i]);
}
return list;
}

private static void printList(LinkedList list) {
Node currentNode = list.getHead();

while(currentNode != null) {
System.out.println(currentNode.getint());
currentNode = currentNode.getNextNode();
}
}

// LinkedList class functions
public void add(int value) {
Node newNode = new Node(value);
Node currentNode;

if(head == null) {
head = newNode;
} else {
currentNode = newNode;

while(currentNode.getNextNode() != null) {
currentNode = currentNode.getNextNode();
}
currentNode.setNextNode(newNode);
}
size++;
}

谁能指出我做错了什么?如果您需要添加任何其他功能,请告诉我,谢谢。

编辑:显示正在添加的值的函数:

private static void processLinkedList() {
int[] values = new int[] {1,2,3,4,5};
LinkedList list = createLinkedList(values);
printList(list);
System.out.println(list);
}

最佳答案

在您的 add() 方法中,

currentNode = newNode;

应该更改为

currentNode = head;

看看这是否能让你前进。

关于java - 链接列表,未正确添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15823554/

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