[Java] ListNode a = new ListNode() -- generates [0] and not null

Any idea how to generate null while creating new ListNode?

Problem I am stuck with : https://leetcode.com/problems/merge-k-sorted-lists

Solution I wrote :

public ListNode mergeKLists(ListNode[] lists) {
        ListNode fin = new ListNode();
        ListNode origHead = fin;
        
        if(lists.length == 0) return null;
        
        while(true) {
            
            int minIndex = -1;
            int minValue = Integer.MAX_VALUE;
            
            for(int i=0;i<lists.length;i++) {
                if(lists[i] != null && lists[i].val < minValue) {
                    minIndex = i;
                    minValue = lists[i].val;
                }
            }
            if(minValue == Integer.MAX_VALUE) return origHead;
            lists[minIndex] = lists[minIndex].next;
            
            fin.val = minValue;
            fin.next = new ListNode();
            fin = fin.next;
            
            
        }
    }

For testcase : image

Zero gets added in the ending. I did get rid of it by adding a counter for null but I feel there's a difference in my understanding about ListNode and this is the same issue I had got stuck with earlier as well.

Thanks.

-------EDIT1-------

Came across this approach that finally worked.

public ListNode mergeKLists(ListNode[] lists) {
        ListNode fin = new ListNode(0);
        ListNode origHead = fin;
        
        if(lists.length == 0) return null;
        
        while(true) {
            
            int minIndex = -1;
            int minValue = Integer.MAX_VALUE;
            
            for(int i=0;i<lists.length;i++) {
                if(lists[i] != null && lists[i].val < minValue) {
                    minIndex = i;
                    minValue = lists[i].val;
                }
            }
            if(minValue == Integer.MAX_VALUE) return origHead.next;
            lists[minIndex] = lists[minIndex].next;
            
            fin.next = new ListNode(minValue);
            fin = fin.next;
            
            
        }
    }

As you can notice, we are returning origHead.next;

And head is default 0. AND, we update our node creation logic to

fin.next = new ListNode(minValue);
fin = fin.next;
Comments (0)