按字母顺序将节点插入链接列表

时间:2019-02-06 20:24:15

标签: java linked-list

我目前正在编写一个将字符串插入到链表中的程序,但是当它插入字符串时,它会按字母顺序对它们进行排序(使用compareTo方法)。我试图覆盖所有可能的边界,并且目前停留在如何插入新节点(如果要在列表的开头)的问题(因此,变量previous为null)。这是我到目前为止的内容:

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());


}

}

1 个答案:

答案 0 :(得分:4)

您只需插入节点:

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