gpt4 book ai didi

Java HW,向 LinkedList 添加 3 个 Int,通过搜索方法仅找到 1 个

转载 作者:行者123 更新时间:2023-12-02 06:14:04 25 4
gpt4 key购买 nike

我创建了一个包含 3 个整数的 LinkedList。我可以通过 toString 打印出这些 int,但是当我尝试遍历列表并打印出每个 int (getData()) 时,它只打印出第一个 int,然后停止,因为下一次迭代指向 null。我从头部开始。为什么我的 head 在 while 循环中指向 null?

主要:

public static void main(String[] args) {

IntNode x = new IntNode(0, null);
int z= 0;
for (int i= 0; i <3; i++){
System.out.println ("Enter an integer");
Scanner keyboard = new Scanner( System.in );
z=keyboard.nextInt();
x.AddNodeAfter(z);
}
System.out.println (x);

这是我的添加方法:

public void AddNodeAfter(int data){
if(head==null){
this.link= new IntNode(data, link);
head=this.link;
counter++;
}
else
{
this.link= new IntNode(data, link);
}
counter++;
}

我还尝试在列表开头使用“添加”:

public void AddAtHead(int data) {

IntNode node = new IntNode(data, link);
node.setData(data);
node.setLink(head);
head=node;
counter++;

}

我遇到问题的地方:

 public void deleteLast(){
if (head==null){
System.out.println("empty list");
}
IntNode current=head;
while(current!=null){
System.out.println("while loop data"+current.getData());
current=current.getLink();

}

我正在构建一个在列表末尾删除的方法,但无法克服这个问题。 while循环只运行一次并打印出first int。 Head 是正确的,但是 it 指向 null,但是列表中还有更多的整数。控制台:

输入一个整数

1

输入一个整数

2

输入一个整数

3

IntNode [数据 = 0,链接 = IntNode [数据 = 3,链接 = IntNode [数据 = 2,链接 = IntNode [数据 = 1,],],],头 = IntNode [数据 = 1,],]

while循环数据

1

最佳答案

扫描仪键盘 = new Scanner( System.in );

应该在 for 循环之外。

this.link 指的是调用您需要稍微修改代码的方法的对象

 if(head==null){
head=n; // variable t should be Instance variable
t=head;
}
else{
t.next=n;
t=t.next;
}

之前的节点下一部分应该指向你当前的新节点......

关于Java HW,向 LinkedList 添加 3 个 Int,通过搜索方法仅找到 1 个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21641466/

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