-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflatten_multilevel_linked_list.cpp
More file actions
68 lines (60 loc) · 1.37 KB
/
flatten_multilevel_linked_list.cpp
File metadata and controls
68 lines (60 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// 430. Flatten a Multilevel Doubly Linked List
// Author: xianfeng.zhu@gmail.com
#include <assert.h>
// Definition for a Node.
struct Node
{
int val;
Node* prev;
Node* next;
Node* child;
Node(int v): val(v), prev(nullptr), next(nullptr), child(nullptr) { }
};
// Recursive
class Solution
{
public:
Node* flatten(Node* head)
{
if (head == nullptr)
{
return head;
}
Node* tail = nullptr;
return flatten(head, &tail);
}
private:
Node* flatten(Node* head, Node** tail)
{
Node* ptr = head;
while (ptr->next != nullptr || ptr->child != nullptr)
{
if (ptr->child != nullptr)
{
Node* follow = ptr->next;
ptr->next = flatten(ptr->child, tail);
ptr->next->prev = ptr;
ptr->child = nullptr;
ptr = *tail;
if (follow != nullptr)
{
(*tail)->next = follow;
follow->prev = *tail;
}
}
if (ptr->next != nullptr)
{
ptr = ptr->next;
}
}
*tail = ptr;
return head;
}
};
int main(int argc, char* argv[])
{
Node* head = nullptr;
head = Solution().flatten(head);
assert(head == nullptr);
return 0;
}