我有一个链表,其中节点包含字符串,我需要编写一个返回字典“最小”的方法。这就是我到目前为止所拥有的。当我进入调试器时,看起来它会将正确的字符串分配给最小但后续继续。它可能与我如何让程序在列表中运行有关,但我不太熟悉在ArrayList或plain数组上使用这种类型的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;
}
答案 0 :(得分:1)
每个节点字符串必须与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;
}
}