将元素添加到单个链接列表中

时间:2013-11-12 19:38:28

标签: java singly-linked-list

我正在编写一个单独链接的整数列表的方法,这些整数将在输入时对它们进行排序。有些东西不正确,因为我的列表都是空的,或者它们中有随机条目。

public void add(int newEntry){
    Node ptr = start;
    Node insert = null;

    Node newNode = new Node(newEntry, null);

    if (start == null)
        start = newNode;

    while (ptr != null && newEntry >= ptr.data){
        ptr = ptr.next;
    }

    if (ptr == start)
        start = newNode;
    else 
        insert = newNode;
}

3 个答案:

答案 0 :(得分:3)

if (start == null)
    start = newNode;

此后您可能希望return,因为您已添加newNode

if (ptr == start)
    start = newNode;

这将导致start的旧值丢失。您可能希望将newNodestart联系起来。

else 
    insert = newNode;

这没有做任何事情,因为insert在其他任何地方都没有使用。

答案 1 :(得分:1)

您没有考虑所有必需的边缘情况。要使此方法有效,请尝试以下方法:

public void add(int newEntry){

    Node newNode = new Node(newEntry, null);

    if (start == null) {
        start = newNode;
    }

    else if (newEntry <= start.data) {
        newNode.next = start;
        start = newNode;
    }

    else {
        Node ptr = start;
        Node prv = null; // save a reference to previous node
        while (ptr != null && newEntry > ptr.data) {
            prv = ptr;
            ptr = ptr.next;
        }
        prv.next = newNode;
        newNode.next = ptr;
    }

}

答案 2 :(得分:1)

我试图尽可能少地改变:

public void add(int newEntry){
    Node ptr = start;
    Node insert = null;

    // the former if is not necessary, will be handled by if at the end

    while (ptr != null && newEntry >= ptr.data){
        insert = ptr; // the node which will point to the new entry
        ptr = ptr.next;
    }

    Node newNode = new Node(newEntry, ptr); // don't forget the rest of the list!

    if (insert == null)
        start = newNode; // first node of empty list or ordered first
    else
        insert.next = newNode; // insertion point found to insert node after
}