forked from Mohammed-Shoaib/Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC0430.cpp
More file actions
executable file
·39 lines (35 loc) · 704 Bytes
/
LC0430.cpp
File metadata and controls
executable file
·39 lines (35 loc) · 704 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
/*
Problem Statement: https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/
Time: O(n)
Space: O(n)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class Solution {
public:
Node* flatten(Node* head) {
stack<Node*> st;
Node *prev = nullptr, *node = head;
while (node) {
prev = node;
if (!node->child)
node = node->next;
else {
st.push(node->next);
assign(node, exchange(node->child, nullptr));
}
if (!node && !st.empty()) {
node = st.top();
st.pop();
assign(prev, node);
}
}
return head;
}
void assign(Node*& node, Node* next) {
if (next)
next->prev = node;
if (node)
node->next = next;
node = next;
};
};