Problem in merge sorted linked lists question

My code is executing in netbeans and giving correct answers. But in your IDE, it is showing error and only one test case is passed. I have checked a number of possible combinations in netbeans and all are executing fine.

please share your code.
thanks

import java.util.*;
public class Main9
{
public class Node
{
int data;
Node next;
Node prev;
}
Node head=null;
Node tail=null;

public void add(int value)
{
    Node node=new Node();
    node.data=value;
    node.next=null;
    if(head!=null)
    {
        node.prev=tail;
        tail.next=node;
        tail=node;   
    }
    else
    {
        head=node;
        tail=node;
        node.prev=null;
    }
}

public void merge(Node head1,Node head2,Main9 newLL)
{
    while(head1!=null&&head2!=null)
    {
        if(head1.data<=head2.data)
        {
            newLL.add(head1.data);
            head1=head1.next;
        }
        else
        {
            newLL.add(head2.data);
            head2=head2.next;
        }
    }
    if(head1==null)
        newLL.tail.next=head2;
    else
        newLL.tail.next=head1;
}

public void display(Node head)
{
    Node node=head;
    while(node!=null)
    {
        System.out.print(node.data+" ");
        node=node.next;
    }
    System.out.println();
}

public static void main(String[] args)
{
    Scanner sc=new Scanner(System.in);
    int T=sc.nextInt();
    for(int i=1;i<=T;i++)
    {
        Main9 LL1=new Main9();
        Main9 LL2=new Main9();
        Main9 newLL=new Main9();
        int j,n;
        int N1=sc.nextInt();
        for(j=1;j<=N1;j++)
        {
            n=sc.nextInt();
            LL1.add(n);
        }
        int N2=sc.nextInt();
        for(j=1;j<=N2;j++)
        {
            n=sc.nextInt();
            LL2.add(n);
        }
        newLL.merge(LL1.head,LL2.head,newLL);
        newLL.display(newLL.head);
    }
}

}

your code won’t work for cases when one of the list is empty at the start.
think about the case like
4
1 2 3 4
0

in this example, list1 has 4 elements, list2 is empty from start, so try to dry run your code, list2.tail will be null and you are trying to access list2.tail.next which will result in run error.

updated code: https://ide.codingblocks.com/s/215058

thanks

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.