有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

数据结构在Java中为链表编写compareTO方法

我有一个链表,其中节点包含字符串,我需要编写一个方法,返回按字典顺序排列的“最小”一个。这就是我目前所拥有的。当我进入调试器时,它看起来会将正确的字符串分配给最小的字符串,但会继续。这可能与我如何让程序在列表中运行有关,但我不太熟悉在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;

}


共 (1) 个答案

  1. # 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;
    
        }
    
    }