430. Flatten a Multilevel Doubly Linked List

problem

solution

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
/*
// Definition for a Node.
class Node {
public:
int val;
Node* prev;
Node* next;
Node* child;
};
*/

class Solution {
public:
Node* flatten(Node* head) {
if(!head) return head;
stack<Node *> sta;
Node *p = head;
// iterative
//flatten linked list
while(p->next || p->child){
if(p->child){
sta.push(p->next);
p->next = p->child;
p->child = nullptr;
}
p=p->next;
}
while(!sta.empty()){
Node *next = sta.top();
sta.pop();
p->next = next;
while(p->next) p=p->next;
}

p=head;
// build bi-direct connection
while(p->next){
p->next->prev = p;

p=p->next;
}
p->next = nullptr;

return head;

}
};

analysis

  • time complexity O(n)
  • space complexity O(n)