I tried to learn how to implement the Doubly Linked List in java as an exercise. but I am stuck in a method remove().
List Content:
1 2 3 4
When I try to remove an item that is not present. It shows NullPointerExceptionat line no. 21instead of printing not found.
The other codes I saw were a bit complicated and different from what I am doing. Method:
void remove(int data){
Node n = head;
if(head==null)
System.out.println("Not Found");
else if(head.d==data){
if(head==tail){
head=null;
tail=null;
}
else{
head=head.next;
head.prev=null;
}
}
else{
while(n!=null && n.d==data){
n=n.next;
}
if(n==tail){
tail=tail.prev;
tail.next=null;
}
else if(n!=null){
n.prev.next=n.next;
n.next.prev=n.prev;
}
if(n==null)
System.out.println("Not Found");
}
}
So my question is: Am I doing this completely wrong? OR what is the problem? Forgive me if this is too stupid.
source
share