我有一个链表,其中节点包含字符串,我需要编写一个方法,该方法将返回字典编纂的"最小"一个。这就是我目前所拥有的。当我进入调试器时,看起来它会将正确的字符串分配给最小字符串,但随后继续。这可能与我如何让程序通过列表运行有关,但我不太熟悉在 ArrayList 或普通数组上使用这种类型的 DT。任何帮助将不胜感激
public String smallest()
LLStringNode node;
node = log;
LLStringNode node2;
node2 = node.getLink();
String smallString = "";
while(node != null)
{
if (node.getInfo().compareTo(node2.getInfo()) <0)
{
smallString = node.getInfo();
node2 = node2.getLink();
}
else if (node.getInfo().compareTo(node2.getInfo()) > 0)
{
smallString = node2.getInfo();
node = node2.getLink();
}
else
break;
}
return smallString;
}
每个节点字符串必须与 smallString 进行比较,而不是与下一个节点进行比较,然后:
package dummy.lexico;
/*
* About LLStringNode, see http://jcsites.juniata.edu/faculty/kruse/cs240/linkedlist1.htm
* or http://www.cs.nyu.edu/courses/fall12/CSCI-GA.1133-001/programs/StringLogs/LLStringNode.txt
*
*/
public class Main {
public static void main(String[] args) {
LLStringNode log = new LLStringNode("toto");
LLStringNode log2 = new LLStringNode("tata");
log.setLink(log2);
LLStringNode log3 = new LLStringNode("t");
log2.setLink(log3);
System.out.println(smallest(log));
}
public static String smallest(final LLStringNode log) {
LLStringNode node = log;
String smallString = log.getInfo();
while (node.getLink() != null) {
node = node.getLink();
final String info = node.getInfo();
if (info == null)
throw new IllegalStateException("Node info should have been filled.");
if (node.getInfo().compareTo(smallString) < 0) {
smallString = node.getInfo();
}
}
return smallString;
}
}