简体   繁体   English

将元素插入已排序的链表中

[英]Inserting an element into an already sorted linked list

I am creating a function that inserts an element into a linked list in the correct order without resorting the list. 我正在创建一个函数,该函数以正确的顺序将元素插入到链表中,而不求助于列表。 Here's the code I have: 这是我的代码:

public void insert(E e) {
    if (e == null)
        throw new NullPointerException();

    if (head == null) {
        head = new Node(e, null);
        count++;
    } else {
        Node current = head;

        for (current = head; current != null ;){
            if(current.item.compareTo(e) > 0){
                Node temp = current;
                current = new Node(e, null);
                current.next = temp;
                break;
            }else{
                current = current.next;
            }
        }
    }   
}

I'm not sure whats going wrong but when I print it out, it only prints out the first element. 我不确定出什么问题了,但是当我打印出来时,它只会打印出第一个元素。 Am I somehow not linking to the head node? 我是否以某种方式不链接​​到头节点? I want it so if it looks through the list and once it finds the item larger then it, it takes that spot and the larger item gets bumped to next. 我想要这样,如果它在列表中查找并且一旦找到更大的项目,它将占据该位置,较大的项目会碰到下一个。 The linked list constructors have already been created outside the list. 链表构造函数已经在链表之外创建。

When you insert a new element into your list, at no point the next reference of the previous element is set: 当您将新元素插入列表时,绝不会设置前一个元素的next引用:

if(current.item.compareTo(e) > 0){
    Node temp = current;
    current = new Node(e, null);
    current.next = temp;
    break;
}else
    \\...

As a consequence, next of the first list element will always point to null , effectively leaving the list empty except for the first element. 结果,第一个list元素的next一个将始终指向null ,实际上将列表保留为空,除了第一个元素。


You also never even try to insert the element if the list is not empty and this condition is false for each list element: 如果列表不为空并且每个列表元素的此条件为false ,您甚至都不会尝试插入该元素:

if(current.item.compareTo(e) > 0){

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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