LeetCode 430. Faltten a Multilevel Doubly Linked List
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 430. Faltten a Multilevel Doubly Linked List相关的知识,希望对你有一定的参考价值。
题目链接:LeetCode 430. Faltten a Multilevel Doubly Linked List
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_iteration(Node *head) {
if (head == NULL) {
return NULL;
}
for (Node *p = head; p != NULL; p = p->next) {
Node *next = p->next;
if (p->child != NULL) {
p->next = p->child;
p->child->prev = p;
p->child = NULL;
Node *tmp = p->next;
while (tmp->next != NULL) {
tmp = tmp->next;
}
tmp->next = next;
next->prev = tmp;
}
}
return head;
}
// 解法二:递归
Node* flatten_recursion(Node *head) {
if (head == NULL) {
return head;
}
Node *p = head;
while (p != NULL) {
if (p->child != NULL) {
Node *next = p->next;
Node *nextLayer = flatten_recursion(p->child);
p->next = nextLayer;
nextLayer->prev = p;
p->child = NULL;
while (nextLayer->next != NULL) {
nextLayer = nextLayer->next;
}
nextLayer->next = next;
if (next != NULL) {
next->prev = nextLayer;
}
}
p = p->next;
}
return head;
}
};
以上是关于LeetCode 430. Faltten a Multilevel Doubly Linked List的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 430. Flatten a Multilevel Doubly Linked List
LeetCode 430 扁平化多级双向链表[递归 栈] HERODING的LeetCode之路
LeetCode——430. 扁平化多级双向链表(Java)