|
| 1 | +/** |
| 2 | + * Title: Flatten a Multilevel Doubly Linked List |
| 3 | + * Description: You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional child pointer. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure as shown in the example below. |
| 4 | + * Author: Hasibul Islam |
| 5 | + * Date: 06/04/2023 |
| 6 | + */ |
| 7 | + |
| 8 | +/** |
| 9 | + * // Definition for a Node. |
| 10 | + * function Node(val,prev,next,child) { |
| 11 | + * this.val = val; |
| 12 | + * this.prev = prev; |
| 13 | + * this.next = next; |
| 14 | + * this.child = child; |
| 15 | + * }; |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * @param {Node} head |
| 20 | + * @return {Node} |
| 21 | + */ |
| 22 | + |
| 23 | +// JavaScript Implementation of zhiying_qian's solution |
| 24 | + |
| 25 | +// Five situations: |
| 26 | +// 1. null - no need to flatten, just return it |
| 27 | +// 2. no child, no next - no need to flatten, it is the last element, just return it |
| 28 | +// 3. no child, next - no need to flatten, go next |
| 29 | +// 4. child, no next - flatten the child and done |
| 30 | +// 5. child, next - flatten the child, connect it with the next, go next |
| 31 | + |
| 32 | +var flatten = function (head) { |
| 33 | + function traverse(node) { |
| 34 | + if (node === null) return node; // CASE 1 |
| 35 | + if (node.child === null) { |
| 36 | + if (node.next === null) return node; // CASE 2 |
| 37 | + else { |
| 38 | + return traverse(node.next); // CASE 3 |
| 39 | + } |
| 40 | + } else { |
| 41 | + let child = node.child; |
| 42 | + node.child = null; |
| 43 | + let next = node.next; |
| 44 | + node.next = child; |
| 45 | + child.prev = node; |
| 46 | + let childtail = traverse(child); |
| 47 | + if (next !== null) { |
| 48 | + // CASE 5 |
| 49 | + childtail.next = next; |
| 50 | + next.prev = childtail; |
| 51 | + return traverse(next); |
| 52 | + } |
| 53 | + return childtail; |
| 54 | + } |
| 55 | + } |
| 56 | + traverse(head); |
| 57 | + return head; |
| 58 | +}; |
| 59 | + |
| 60 | +var Node = function (val, prev, next, child) { |
| 61 | + this.val = val; |
| 62 | + this.prev = prev; |
| 63 | + this.next = next; |
| 64 | + this.child = child; |
| 65 | + |
| 66 | + this.child = null; |
| 67 | + this.next = null; |
| 68 | + this.prev = null; |
| 69 | +}; |
| 70 | + |
| 71 | +console.log( |
| 72 | + flatten( |
| 73 | + new Node( |
| 74 | + 1, |
| 75 | + null, |
| 76 | + null, |
| 77 | + new Node( |
| 78 | + 2, |
| 79 | + null, |
| 80 | + null, |
| 81 | + new Node( |
| 82 | + 3, |
| 83 | + null, |
| 84 | + null, |
| 85 | + new Node(4, null, null, new Node(5, null, null, null)) |
| 86 | + ) |
| 87 | + ) |
| 88 | + ) |
| 89 | + ) |
| 90 | +); |
0 commit comments