Leetcode 430. Flatten a Multilevel Doubly Linked List

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Flatten a Multilevel Doubly Linked List

2. 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 = NULL;
Node* prev = NULL;
Node* next = NULL;
Node* child = NULL;

Node() {}

Node(int _val, Node* _prev, Node* _next, Node* _child) {
val = _val;
prev = _prev;
next = _next;
child = _child;
}
};
*/
class Solution {
public:
Node* flatten(Node* head) {
stack<Node*> nodes;
Node* current = head;
Node* pre = nullptr;
while(current) {
if(current->child) {
if(current->next) {
nodes.push(current->next);
}
current->next = current->child;
current->next->prev = current;
current->child = nullptr;
}
pre = current;
current = current->next;
if(!current && !nodes.empty()) {
Node* temp = nodes.top();
nodes.pop();
pre->next = temp;
temp->prev = pre;
current = temp;
}
}
return head;
}
};

Reference

  1. https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/description/
如果有收获,可以请我喝杯咖啡!