Skip to content

Commit 00f5917

Browse files
committedFeb 27, 2025
Add solution #430
1 parent 371dc80 commit 00f5917

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -341,6 +341,7 @@
341341
424|[Longest Repeating Character Replacement](./0424-longest-repeating-character-replacement.js)|Medium|
342342
427|[Construct Quad Tree](./0427-construct-quad-tree.js)|Medium|
343343
429|[N-ary Tree Level Order Traversal](./0429-n-ary-tree-level-order-traversal.js)|Medium|
344+
430|[Flatten a Multilevel Doubly Linked List](./0430-flatten-a-multilevel-doubly-linked-list.js)|Medium|
344345
434|[Number of Segments in a String](./0434-number-of-segments-in-a-string.js)|Easy|
345346
435|[Non-overlapping Intervals](./0435-non-overlapping-intervals.js)|Medium|
346347
437|[Path Sum III](./0437-path-sum-iii.js)|Medium|
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/**
2+
* 430. Flatten a Multilevel Doubly Linked List
3+
* https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/
4+
* Difficulty: Medium
5+
*
6+
* You are given a doubly linked list, which contains nodes that have a next pointer, a previous
7+
* pointer, and an additional child pointer. This child pointer may or may not point to a separate
8+
* doubly linked list, also containing these special nodes. These child lists may have one or more
9+
* children of their own, and so on, to produce a multilevel data structure as shown in the example
10+
* below.
11+
*
12+
* Given the head of the first level of the list, flatten the list so that all the nodes appear in
13+
* a single-level, doubly linked list. Let curr be a node with a child list. The nodes in the child
14+
* list should appear after curr and before curr.next in the flattened list.
15+
*
16+
* Return the head of the flattened list. The nodes in the list must have all of their child
17+
* pointers set to null.
18+
*/
19+
20+
/**
21+
* // Definition for a _Node.
22+
* function _Node(val,prev,next,child) {
23+
* this.val = val;
24+
* this.prev = prev;
25+
* this.next = next;
26+
* this.child = child;
27+
* };
28+
*/
29+
30+
/**
31+
* @param {_Node} head
32+
* @return {_Node}
33+
*/
34+
var flatten = function(head) {
35+
if (!head) return null;
36+
37+
let current = head;
38+
while (current) {
39+
if (!current.child) {
40+
current = current.next;
41+
} else {
42+
const { child, next } = current;
43+
current.child = null;
44+
current.next = child;
45+
child.prev = current;
46+
47+
let tail = child;
48+
while (tail.next) {
49+
tail = tail.next;
50+
}
51+
52+
tail.next = next;
53+
if (next) {
54+
next.prev = tail;
55+
}
56+
current = current.next;
57+
}
58+
}
59+
60+
return head;
61+
};

0 commit comments

Comments
 (0)
Please sign in to comment.