在已排序的链接列表中插入节点

时间:2014-08-13 18:36:21

标签: java data-structures linked-list

enter image description here

以下代码确保元素以排序方式插入链接列表中。

在理解了背后的逻辑后,我决定自己测试它。但是,当我编写我的代码版本时,如下所示。

  public class SortedList {

    private Node first;

    public SortedList() {
        first = null;
    }

    public boolean isEmpty() {
        return first == null;
    }

    public void insert(int j) {
        Node newNode = new Node(j);
        Node previous = null;
        Node current = first;

        while (current != null && j > current.iData) {
            previous = current;
            current = current.next;
        }

        if (previous == null)
            first = newNode;

        else

            newNode.next = current;
        previous.next = newNode;

    }

    public Node remove() {
        Node temp = first;
        first = first.next;
        return temp;
    }

    public void displayList() {
        System.out.println("First to -----> Last");
        Node current = first;

        while (current != null) {
            current.display();
            current = current.next;
        }
    }

}

NODE CLASS

public class Node {

    public int iData;
    public Node next;

    public Node(int id) {
        iData = id;
    }

    public void display() {
        System.out.println(iData + " ");
    }

}

TEST CLASS

public class SortedListApp {

    public static void main(String[] args) {

        SortedList list = new SortedList();

        list.insert(20);
        list.insert(40);

        list.displayList();

        list.insert(10);
        list.insert(30);
        list.insert(50);

        list.displayList();

        list.remove();

        list.displayList();

    }

}

两者之间的唯一区别是在我的版本中while循环终止。我首先将newNode的下一个值设置为当前值,然后将新节点的上一个值设置为。在发布的原始代码中,它们已经颠倒了。由于某种原因,这会抛出Null Pointer Exception。我想知道为什么?

据我所知,一旦新节点找到了插入的位置。我们引用了前一个节点和当前节点,我们试图将新节点插入到前一个节点和当前节点的中间。因此,我所做的是将新节点的下一个设置为当前节点,然后将前一个节点的下一个节点设置为新节点。

请告诉我哪里错了。

1 个答案:

答案 0 :(得分:2)

previous为空时跟踪此代码:

if (previous == null)
    first = newNode;
else
    newNode.next = current;
previous.next = newNode;

请注意,您从未真正更改过previous语句中的if,因此会尝试编写next null字段,从而导致崩溃。

如果previous为空,那么您需要将该节点添加到列表中,在这种情况下,您需要做的就是将first设置为newNode并使{{1}下一个指针指向旧列表。在newNode不是previous的情况下,您需要进行两次重写:您需要将null指向新节点并指向新节点&#39}。下一个指向当前节点的指针。您可以通过编写

来解决此问题
previous.next

等效地:

if (previous == null) {
    newNode.next = current;
    first = newNode;
}
else {
    newNode.next = current;
    previous.next = newNode;
}

希望这有帮助!

相关问题