Message on Whatsapp 8879355057 for DSA(OA + Interview) + Fullstack Dev Training + 1-1 Personalized Mentoring to get 10+LPA Job
0 like 0 dislike
592 views
in Online Assessments by Expert (34,270 points) | 592 views

2 Answers

0 like 0 dislike
Here my solution


public class Solution {

    private static class ListNode {
        int val;
        ListNode next;
        ListNode down;
        public ListNode(int val, ListNode next, ListNode down) {
            this.val = val;
            this.next = next;
            this.down = down;
        }
    }

    public static void main(String args[]) throws Exception {
        ListNode three = new ListNode(3, null, null);
        ListNode two = new ListNode(2, null, null);
        ListNode one = new ListNode(1, two, three);

        BloombergWebAPiRound1 sol = new BloombergWebAPiRound1();
        sol.flatten(one);
        ListNode temp = one;
        while (temp != null) {
            System.out.print(temp.val + " ");
            temp = temp.next;
        }
    }


    private ListNode flatten(ListNode head) {
        if (head == null)
            return null;
        ListNode next = head.next;
        ListNode down = head.down;
        if (head.down != null) {

            head.next = down;
            ListNode tempDown = down;
            ListNode prev = head;

            while (tempDown != null) {
                prev = down;
                if (tempDown.down != null) {
                    flatten(tempDown);
                }
                tempDown = tempDown.next;
            }
            if (next != null)
                prev.next = next;

            head.down = null;
        }
        flatten(next);
        return head;
    }
}
by Expert (34,270 points)
0 like 0 dislike
The Question was to flatten a linkedList with downNode values.

 

eg :
1 - 2 to 1-3-2
|
3
by Expert (34,270 points)