gpt4 book ai didi

java - 只打印链表的最后两个值

转载 作者:太空宇宙 更新时间:2023-11-04 06:13:29 25 4
gpt4 key购买 nike

这是我的 Node 类

public class listNode {
String data;
listNode next;

public listNode(String data, listNode next) {
this.data = data;
this.next = next;
}

public String toString(){
return data;
}
}

她是我的列表类

public class List {
listNode head;

public List(){
head = null;
}

public void addLast(String target){
if(head == null){
head = new listNode(target,head);
}
while(head.next != null){
head = head.next;
}
head.next = new listNode(target,null);
}
}

打印方法:

public void print(){
while(head != null){
System.out.println(head.toString());
head = head.next;
}
}

当我在主函数中使用这个方法时,它总是只打印链表的最后两个值,我很困惑。

示例:

l1.addLast("a");
l1.addLast("b");
l1.addLast("c");

它只打印

b,c

最佳答案

下面的代码是错误的。您不应该更改头部对象。使用不同的对象。

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

应该是这样的:

class List {
listNode head;

public List(){
head = null;
}

public void addLast(String target){
if(head == null){
head = new listNode(target,head);
}
else {
listNode last = head;
while(last.next != null){
last = last.next;
}
last.next = new listNode(target,null);
}

}
}

关于java - 只打印链表的最后两个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28402556/

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