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.