File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ /* Definition of MultiLevelListNode:
2
+ class MultieLevelListNode {
3
+ val: number; next: MLLNode; child: MLLNode;
4
+ constructor(val: number){
5
+ this.val = val;
6
+ this.next = null;
7
+ this.child = null;
8
+ }
9
+ }
10
+ type MLLNode = MultieLevelListNode | null;
11
+ */
12
+
13
+ function flattenMultiLevelList ( head : MLLNode ) : MLLNode {
14
+ if ( ! head )
15
+ return head ;
16
+ let tail : MLLNode = head ;
17
+ // Find the tail of the linked list at the first level.
18
+ while ( tail . next !== null )
19
+ tail = tail . next ;
20
+ let curr : MLLNode = head ;
21
+ // Process each node at the current level. If a node has a child linked list,
22
+ // append it to the tail and then update the tail to the end of the extended
23
+ // linked list. Continue until all nodes at the current level are processed.
24
+ while ( curr !== null ) {
25
+ if ( curr . child !== null ) {
26
+ tail . next = curr . child ;
27
+ // Disconnect the child linked list from the current node.
28
+ curr . child = null ;
29
+ while ( tail . next !== null )
30
+ tail = tail . next ;
31
+ }
32
+ curr = curr . next ;
33
+ }
34
+ return head ;
35
+ }
You can’t perform that action at this time.
0 commit comments