Problem: Given a linked list where in addition to the next pointer, each node has a child pointer, which may or may not point to a separate list. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure. You are given the head of the first level of the list.
Flatten the list so that all the nodes appear in a single-level, doubly linked list.
Example(taken from leetcode):
Input: head = [1,2,null,3] Output: [1,3,2] Explanation: The input multilevel linked list is as follows: 1---2---NULL | 3---NULL
Approach: This is similar to the problem Amazon Question: Flatten a multilevel linked list. In the previous problem we need to flatten the list level by level but here a node's child will come before the next.
We can use stack / recursion to solve this problem. I am using stack in my implementation.
Implementation in C#:
public Node Flatten(Node head)
{
Node itr = head;
Stack<Node> stack = new Stack<Node>();
while (itr?.next != null || itr?.child != null || stack.Count > 0)
{
if (itr.next == null && itr.child == null)
{
var node = stack.Pop();
itr.next = node;
node.prev = itr;
}
if (itr.child != null)
{
if (itr.next != null)
{
stack.Push(itr.next);
}
itr.next = itr.child;
itr.child.prev = itr;
itr.child = null;
}
itr = itr.next;
}
return head;
}
Complexity: O(n)
No comments:
Post a Comment