DSeverns
DSeverns

Reputation: 13

Writing a compareTO method for a linked list in Java

I have a linked list where the nodes contain strings and I need to write a method that will return the lexicographical "smallest" one. This is what I have so far. when I go into the debugger it looks like it will assign the correct string to smallest but then keep going. It may have to do with how I have the program running through the list but I am not too familiar with using this type of DT over an ArrayList or plain array. Any help would be greatly appreciated

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;

}

Upvotes: 0

Views: 647

Answers (1)

atao
atao

Reputation: 845

Each node string must be compare with smallString, not with the next node, then:

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;

    }

}

Upvotes: 1

Related Questions