Skip to content

Commit 539d2ed

Browse files
committed
ts-3: flatten list
1 parent dc941b6 commit 539d2ed

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
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+
}

0 commit comments

Comments
 (0)