-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFlattenaMultilevelDoublyLinkedList.cpp
More file actions
48 lines (44 loc) · 1021 Bytes
/
Copy pathFlattenaMultilevelDoublyLinkedList.cpp
File metadata and controls
48 lines (44 loc) · 1021 Bytes
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
#include <vector>
using namespace std;
class Node {
public:
int val;
Node* prev;
Node* next;
Node* child;
Node() {}
Node(int _val, Node* _prev, Node* _next, Node* _child) {
val = _val;
prev = _prev;
next = _next;
child = _child;
}
};
class Solution {
public:
Node *tail;
Node* flatten(Node* head) {
tail = nullptr;
flatten_list(head);
return head;
}
void flatten_list(Node *head){
Node *p = head;
while(p != nullptr){
if(p->child != nullptr){
Node *next_node = p->next;
p->next = p->child;
p->child = nullptr;
p->next->prev = p;
flatten_list(p->next);
tail->next = next_node;
if(next_node != nullptr) next_node ->prev = tail;
p = next_node;
}
else {
tail = p;
p = p->next;
}
}
}
};