从文件读取java链表、排序和offbyone错误
我必须创建一个链表来读取字符串和相关int的文件,并在读取时按int进行排序。到目前为止,我已经获得了一个向列表中添加元素的方法和一个基本读取方法(但由于某种原因缺少文件中的最后一个元素),但每次我尝试向读取方法添加条件时,它返回一个空列表
我的添加方法:
public void addFirst(String name, int rank)
{
Ship newShip = new Ship(name, rank);
if (isEmpty())
{
newShip.next = null;
newShip.prev = null;
last = newShip;
first = newShip;
}
else
{
first.next = newShip;
newShip.prev = first;
first = newShip;
}
}
以及我的工作(但只需一次)读取方法:
public void readFile(String filename) throws IOException
{
try
{
File inFile = new File(filename); //inst. file import
Scanner read = new Scanner(inFile); //inst. scanner object
while (read.hasNext()) //reads until end of text
{
String name = read.next(); //scanner reads next string, assigns to name
int rank = read.nextInt(); //reads next int, assigns to rank
addFirst(name, rank); //enqueues ship name and rank into list
}
read.close(); //ends read when empty
}
catch(IOException exc)
{
System.out.println("Error: file not found");
}
}
每次我向read方法中的while()添加一个条件时,就像这样(数据文件中有一个“0”):
while (read.hasNext()) //reads until end of text
{
String name = read.next(); //scanner reads next string, assigns to name
int rank = read.nextInt(); //reads next int, assigns to rank
if (rank == 0)
{
addFirst(name, rank); //enqueues ship name and rank into list
}
}
Tt似乎根本没有读过这个列表。如果我不能弄清楚add方法被破坏的原因,我就不能开始在插入算法中添加条件
编辑:添加示例数据集。我只需要弄清楚我在概念上把事情搞砸了
10号船 船舶2 10 船舶3 27 船舶4 2 船舶5 7 ....
编辑2:
好的,现在放弃使用链表来计算插入,只创建一个基于sentinel的插入read()方法。谢谢你的帮助
# 1 楼答案
我试过使用你的
readFile
方法,它似乎对我很好,正确地读取文件! 但是您的addFirst(String name, int rank)
中似乎有一个错误在
else
条件中,您实际要做的是将newShip
添加为第二个元素(在第一个元素之后),但您没有注意到第一个元素之后可能有更多的项!您也不关心newShip
的next
例如:如果您的列表是::(尽管使用代码,您将无法创建这样的链接列表!示例仅用于解释)
1< >2< >3 >NULL
first
指向1
然后在添加新元素之后
4
您的链接将如下所示:
1< >4< >DANGLING
first
指向4
及
1< 2< >3 >NULL
{注意我用过的尖括号,它是指针的方向
似乎您正试图添加到链接列表的前面! 所以,你的代码应该是这样的
# 2 楼答案
只是在这里问一下,因为它太大了,无法发表评论:
假设
addFirst
方法用于添加到链接列表的头部,并且船舶确实具有属性next
和prev
,您不希望:或者,如果要在链接列表的末尾添加,您不希望:
不管怎样,你所拥有的似乎并不正确。如果我错了,请纠正我