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;
}
}