user4833678
user4833678

Reputation:

Inserting into the sorted linked list

Im getting nullpointerexception in this line:

while(data > current.data)

I have an ordered list that is sorted in ascending order, i.e. the insertInPos() inserts a node in a proper position. But why am I getting 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;
        }
    }

main Class

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

Upvotes: 0

Views: 39

Answers (1)

afzalex
afzalex

Reputation: 8652

You are getting error because current become null at the end of your list.

Change your condition to following

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

Upvotes: 1

Related Questions