简体   繁体   中英

Trying to add string objects into a linked list in alphabetical order by using compareTo but I am stuck on inserting elements in the middle. Java

public void addElement(Object element)
{
    if(first == null) //empty list 
    {
        addFirst(element);
    }
    else 
    {
        //having these move
        boolean cloud = true;
        LinkedListIterator hamsters = new LinkedListIterator();
        while (hamsters.hasNext() && cloud) //while there are elements in the list.
        {
            //getting strings to compare
            String str = (String) element; //string entered
            System.out.println(str +" is string I just entered");
            String str2 = (String) hamsters.next();
            System.out.println(str2 +" is string inside the list");

            //if string entered is greater than second string, then insert new node. 
            if(str.compareTo(str2) > 0 || str.compareTo(str2) == 0)
            {
                hamsters.add(element);
                cloud = false;
            }
        }
    }

The problem with this code is that it only compares with the first element (and inserts the element after the first element) in the linked list. So if I enter something like "apple, banana, cat", it will print "apple, cat, banana," when I need it to print, "apple, banana, cat."

Any suggestions?

Edit: Here's the iterator --> https://gist.github.com/bettyjing/84ee94b73713226ba8ad

You should not be inserting the a new node right after the first element in the list that is less than the new one. You should be inserting it before the first element in the list that is greater than the new one (or at the end if none in the list is greater).

Try this:

while (hamsters.hasNext() && cloud) //while there are elements in the list.
{
    //getting strings to compare
    String str = (String) element; //string entered
    System.out.println(str +" is string I just entered");
    String str2 = (String) hamsters.next();
    System.out.println(str2 +" is string inside the list");

    //if string entered is less than second string, then insert new node before it. 
    if(str.compareTo(str2) < 0 || str.compareTo(str2) == 0)
    {
        hamsters.previous();
        hamsters.add(element);
        cloud = false;
    }
}
if (cloud) 
{
    hamster.add(element);
}

Looks like your LinkedListIterator never actually gets initialized. You start with

  position = null;
  previous = null;

and you never actually set them to anything in the code I see. On the other hand, if that's the problem then your loop should just quit immediately, so is there something else going on?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM