Reputation:
emphasized text i need to pass header of the LINKED LIST and data to be inserted in that linked list.assuming the list is in sorted order i need to check data from each node and insert new node to give newly sorted list.
im getting null pointer exception ,, i need to know what im doing wrong
/*
Insert Node at the end of a linked list
head pointer input could be NULL as well for empty list
Node is defined as
class Node {
int data;
Node next;
Node prev;
}
*/
Node SortedInsert(Node head,int data) {
Node root= head;
if(head==null){
root.data=data;
root.next=null;
root.prev=null;
}else if(head.data>data){
Node newnode = new Node();
newnode.data=data;
newnode.next=head;
newnode.prev=null;
head.prev=newnode;
root=newnode;
}
int k=0;
while(head!=null && k==0){
if(head.data<data && head.next.data>data && head.next!=null){
Node temp=head.next;
Node newnode = new Node();
newnode.data=data;
newnode.next=temp;
newnode.prev=head;
head.next=newnode;
temp.prev=newnode;k++; break;
}
else if(head.data<data && head.next==null){
//Node temp=head.next;
Node newnode = new Node();
newnode.data=data;
newnode.next=null;
newnode.prev=head;
head.next=newnode;k++;break;
//temp.prev=newnode;
}else
{head=head.next;}
}
return root;
}
im getting null pointer exception at second if statement inside while loop.
Upvotes: 0
Views: 357
Reputation: 2489
I found some errors in your code which might be giving NullPointerException
So change it accordingly.
First mistake is here:
Node root= head;
if(head==null){
root.data=data;
root.next=null;
root.prev=null;
}
So here you need to first create an object of Node class and assign it to root so code will look like :
Node root= head;
if(head==null){
root=new Node();
root.data=data;
root.next=null;
root.prev=null;
}
Another Mistake I encountered is in condition of if(head.data<data && head.next.data>data && head.next!=null)
.
Here you are should validate head.next
before accessing it in head.next.data
.
Suppose if head.next
is null
then the evaluation of condition
of loop goes like this.
1) head.data<data
so suppose this return true
so we will check next condition.
2) head.next.data>data
now if head.next
is null
then here condition would be null.data
which will throw an NullPointerException
. So here you should also check that head.next
is not null. You are doing this is next condition but it is getting executed before validation it.
So here you just need to change order of the condition of if
statement like: if(head.data<data && head.next!=null && head.next.data>data)
.
This will solve your problem.
Upvotes: 1
Reputation: 330
Node root= head;
if(head==null){
root.data=data;
here you are trying to set data for a null object you should allocate memory for root first e.g.
head = new Node();
root = head
//then continue your code
Upvotes: 0