插入已排序的链接列表

时间:2015-10-22 05:00:16

标签: java linked-list

我在这一行得到nullpointerexception

while(data > current.data)

我有一个按升序排序的有序列表,即insertInPos()将节点插入正确的位置。但为什么我会nullpointer

public void insertInPos(int data){
        if(head == null){
            head = new Node(data, null);
        }
        else if(head.data > data){
            Node newNode = new Node(data, null);
            newNode.next = head;
            head = newNode;
        }
        else{
            Node newNode = new Node(data, null);
            Node current = head;
            Node previous = null;
            while(data > current.data){
                previous = current;
                current = current.next;
            }
            previous.next = newNode;
            newNode.next = current;
        }
    }

主要类

public class Tester {

    public static void main(String[] args){
        LinkedList myList = new LinkedList();
        myList.insertInPos(1);
        myList.insertInPos(2);//Getting nullpointer from here
        myList.insertInPos(3);
        myList.insertInPos(4);
        myList.insertInPos(7);
        myList.insertInPos(7);
        myList.insertInPos(8);
        System.out.println();

        myList.displayList();
    }
}

1 个答案:

答案 0 :(得分:1)

您收到错误是因为current在您的列表末尾变为null

将您的情况更改为以下

while(current != null && data > current.data){
    previous = current;
    current = current.next;
}
相关问题