编辑: 对不起,这里是我调用insert()方法的代码。现在无限循环消失了,但插入(else ...)中的最后一种情况仍然不会按顺序添加字符串。按字母顺序排列的字符串插入Java链接列表
public static void main(String[] args)
{
Frequency f = new Frequency();
String s1 = "apple";
String s2 = "crayon";
String s3 = "bear";
String s4 = "apple";
String s5 = "";
f.insert(s1);
f.insert(s2);
f.insert(s3);
f.insert(s4);
f.insert(s5);
f.print();
}
输出测试: (苹果,2)(蜡笔,1)
我收到了我的大学课程的一个项目,需要我插入字符串到按字母顺序的链接列表。我想我有正确的方法,但运行该程序会导致无限循环;我不知道为什么。这里是我到目前为止的代码,我宁愿一个解释过的代码:
/*
* Inserts a word into the linked list. If the word exists, increment the
* count by q.
*/
public void insert(E word){
//word is empty
if(word.equals("")){
return;
}
//list is empty
else if(isEmpty())
{
Node n = new Node(word);
first = n;
N++;
}
//list already has word
else if(contains(word))
{
Node cur = first;
while(cur != null)
{
if(cur.key == word)
cur.count++;
cur = cur.next;
}
}
//list only has 1 object
else if(N == 1)
{
Node n = new Node(word);
first.next = n;
N++;
}
//inserting new object
else
{
Node n = new Node(word);
Node cur = first;
while(cur != null)
{
if(cur.next != null)
{
if(cur.next.key.compareTo(word) <= 0)
{
Node temp = cur.next;
cur.next = n;
n.next = cur.next;
return; //exit, since the word has been added
}
cur = cur.next;
}
else
cur.next = n;
}
N++;
}
}
您实际上正在调用'insert()'的代码在哪里? –
分享你的代码插入方法...... – CoderNeji
'== word'应该是一个'equals'或'的compareTo == 0'。 –