Bloomberg Interview Question

Flatten a 2D linkedList . A node contains 3 parameters namely, data , pointer to left, pointer to down . The aim of the function is to flatten the linkedlist. Ex: 1-->2-->4 | V 3 Answer is 1-->2-->3-->4 Ex: 1 --> 2--> 3--> 4 | 5-->6-->7 | | 8 9 Answer is 1-->2->5 -> 8 -> 6->9 ->7-> 3-> 4 He asked me to make the same linkedlist flatten not to create a new LinkedList or print the elements

Interview Answers

Anonymous

Mar 10, 2015

public static Dnode flatten(Dnode root){ if(root==null) return null; Dnode nextpoint= root.right; if(root.down!=null){ root.right=flatten(root.down); root.down=null; Dnode pointer=root.right; while(pointer.right!=null){ pointer=pointer.right; } pointer.right=nextpoint; } flatten(nextpoint); return root; }

3

Anonymous

Apr 27, 2015

It can be flatten in place as follows private static void flatten(Node n) { while (n != null) { if (n.down != null) { Node temp = n.next; n.next = n.down; Node tail = returnTail(n.next); tail.next = temp; } n = n.next; } } private static Node returnTail(Node n) { Node tail = null; while (n != null) { tail = n; n = n.next; } return tail; }

1

Anonymous

Mar 6, 2015

I used a stack . I traverse through the linked list. If I encounter a node with down pointer I save the next pointer of the node to the stack . I traverse until the end and then pop the elements from stack check if the enxt pointer is not null . If not null traverse untill the next pointer is null and then pop the top of the stack again until the stack is empty