Reputation: 1
My issue is with the while loop at the end of my function
public void insertInOrder(int i){
Node temp;
if(head == null){
head = new Node(i,null);
}
else if (head.getData() > i){
temp = new Node(i,head);
head = temp;
}
else {
Node curr = head;
while (curr.getNext() != null && curr.getNext().getData() <= i);
while(curr.getNext().getData() <= i)
curr = curr.getNext();
temp = new Node(i,curr.getNext());
curr.setNext(temp)
In order to enter the while loop i need to have my next node in my linked list not equal to null and it must be less than i. This works until i send through a value that leads to the end of my list and i get a null pointer exception error since the second statement can't evaluate. How can i get around this?
Upvotes: 0
Views: 135
Reputation: 395
Remove the semicolon at the end of your statement
while (curr.getNext() != null && curr.getNext().getData() <= i);
<----
Upvotes: 0
Reputation: 15533
I think you have a trailing semicolon that should not be there:
---------------------------------------------------------------v
while (curr.getNext() != null && curr.getNext().getData() <= i);
while(curr.getNext().getData() <= i)
curr = curr.getNext();
Remove it and your code should work, in my opinion.
This kind of mistakes is one of the reasons why you should always use curly braces even when they do not seem necessary. So I would rewrite the while loop like this:
while (curr.getNext() != null && curr.getNext().getData() <= i) {
while(curr.getNext().getData() <= i) {
curr = curr.getNext();
}
}
Upvotes: 3