简体   繁体   中英

Inserting nodes into a linked list alphabetically

I am currently writing a program that inserts strings into a linked list but when it inserts the strings, it sorts them alphabetically (using the compareTo method). I am trying to cover all the possible boundaries and am currently stuck on how to insert a new node if it is to go at the beginning of the list (thus, the variable previous is null). This is what I have so far:

public class LinkedList{
private Node root;
private Node tail;

public void add(String data){
    Node current = root;
    Node previous = null;
    Node newNode = new Node(data);
    if(root == null){
        root = newNode;
        tail = root;
        newNode.next = null;
        return;
    }
    for( ; current != null; previous = current, current = current.next){
        if(newNode.data.compareTo(current.data)<= 0){
            break;
        }
    }
    if(previous != null){
        newNode.next = current;
        previous.next = newNode;
        if(current == null) { 
            tail = newNode;
        }
    } else{ 
        // if Previous IS null
        previous = newNode;        //The code that does not work as expected
        newNode.next = current; 

    }
}

public static final void main(String[] args){
    LinkedList list = new LinkedList();
    // for(int i = 0; i < 10; i++){
    //     list.add("Item");
    // }
    list.add("Item1");
    list.add("Item2");
    list.add("Item4");
    System.out.println(list.toString());
    list.add("Item3");
    System.out.println(list.toString());
    list.add("Item3");
    System.out.println(list.toString());
    list.add("Item0");
    System.out.println(list.toString());


}

}

You just have to insert the node:

  else{ 
      // if Previous IS null
      newNode.next = root;
      root=newNode;
 }

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