gpt4 book ai didi

java - LinkedList 无法添加 LLNode

转载 作者:行者123 更新时间:2023-12-02 08:03:59 25 4
gpt4 key购买 nike

我正在创建一个读取到扫描仪中的整数文件。扫描器生成一个 Job 的 LinkedList,每个 Job 包含 5 个 int 值。然后使用 MergeSort 对这些作业进行排序并进行调度。即使文件中有数百个值,生成的计划也只会返回一个值。

我已经确定 Iterable 和 Mergesort 都工作正常。该错误存在于 LinkedList 创建过程中的某个地方。

我的代码直到错误区域显示如下:

public JobSchedule makeSchedule(JobSchedule.Metric metric, Job.JobOrdering ordering){
Scanner s = new Scanner(file);
SortableLinkedList<Job> sortable = new SortableLinkedList<Job>();
LLNode<Job> listptr = sortable.getHead();
//reads the contents of file into a storage array and...
// ...inputs the stored values as parameters for Job constructors
while(s.hasNext()){
int[] ints = new int[5];
for(int i = 0; i<5; i++){
ints[i]=s.nextInt();
}

我验证它是否正确设置了头部:

    if(sortable.getHead()==null){
sortable.setHead(new LLNode<Job>(new Job(ints[0],ints[1],
ints[2],ints[3],ints[4]),null));
sortable.getHead().getElement().setOrdering(ordering);
listptr = sortable.getHead();
}

我认为这是程序失败的地方:

    else{
listptr.setNext(new LLNode<Job>(new Job(ints[0],ints[1],
ints[2],ints[3],ints[4]),null));
listptr = listptr.getNext();
}
}

尽管在我的错误测试中(放置在上面的 else block 中):

 System.out.println("Next:"+ints[0]+" "+ints[1]+" "+ints[2]+" "+ints[3]+" "+ints[4]);

每次迭代都成功打印。

有什么想法吗?

ps。 LLNode和LinkedList代码:

public class LLNode<T>{  
private T element;
private LLNode<T> next;


public LLNode(T element, LLNode<T> next){
this.element = element;
this.next = next;
}

public T getElement(){
return this.element;
}

public LLNode<T> getNext(){
return this.next;
}

public void setNext(LLNode<T> node){
this.next=node;
}
}



public class LinkedList<T>{
private LLNode<T> head;

public LinkedList(){
head = null;
}

public LinkedList(LLNode<T> head){
this.head = head;
}

public LLNode<T> getHead(){
return head;
}

public void setHead(LLNode<T> node){
this.head = node;
}
}

最佳答案

这段代码:

while(s.hasNext()){
int[] ints = new int[5];
for(int i = 0; i<5; i++){
ints[i]=s.nextInt();
}

创建一个 5 int 数组,如果文件中有更多 int 数组,它会销毁新创建的数组并创建一个新数组。它一直持续到文件中不再有 int 为止。 while 循环结束后最好的情况是你只有一个 5 ints 数组。这是你的意图吗?

换句话说,您的整数数组最多存储文件中的最后 5 个整数。您应该在循环中包含某种 addToList(ints) 方法,或者将 5 个整数数组存储在 ArrayList 中,然后在创建作业并将它们添加到链接列表时一一检索它们。

关于java - LinkedList 无法添加 LLNode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8454714/

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