繁体   English   中英

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

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

我正在创建一个函数,该函数以正确的顺序将元素插入到链表中,而不求助于列表。 这是我的代码:

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;
            }
        }
    }   
}

我不确定出什么问题了,但是当我打印出来时,它只会打印出第一个元素。 我是否以某种方式不链接​​到头节点? 我想要这样,如果它在列表中查找并且一旦找到更大的项目,它将占据该位置,较大的项目会碰到下一个。 链表构造函数已经在链表之外创建。

当您将新元素插入列表时,绝不会设置前一个元素的next引用:

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

结果,第一个list元素的next一个将始终指向null ,实际上将列表保留为空,除了第一个元素。


如果列表不为空并且每个列表元素的此条件为false ,您甚至都不会尝试插入该元素:

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

暂无
暂无

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

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