How to print out all values inside of a ListNode array

Hello I am trying to print out all the values inside of a ListNode array, but can only seem to print out the values of the first index for each ListNode.

Here is the data contained inside the ListNode array.
ListNode[] lists = {[1,4,3], [1,3,4], [2,6]}

The output comes out as -> [1, 1, 2]

Expected -> [1, 4, 5, 1, 3, 4, 2, 6]

Any help is appreciated.

class ListNode {
    int val;
    ListNode next;

    public ListNode(){}

    public ListNode(int val){
        this.val = val;
    }

    public ListNode(int val, ListNode next){
        this.val = val;
        this.next = next;
    }
}

public static void main(String[] args) {
        //listnode array full of 3 indices of listnodes
        
        
        ListNode lists[] = {new ListNode(1, new ListNode(4, new ListNode(5))),
            new ListNode(1, new ListNode(3, new ListNode(4))),
            new ListNode(2, new ListNode(6))
        }; 
        

       for(ListNode ln : lists){
        System.out.print(ln.val + ", ");
       }
    }

>Solution :

The best way would be to have a recursive function that takes a Node and then if it has next then pass this next node to itself.

But otherwise, if you are sure that the array will only be 2D, then something like inner loop

for(ListNode ln : lists){
    System.out.print(ln.val + ", ");
    ListNode ln2 = ln.next;
    while (ln2 != null) {
        System.out.print(ln2.val + ", ");
        ln2 = ln2.next;
    }
}

Leave a Reply