Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading