📅  最后修改于: 2023-12-03 15:27:10.938000             🧑  作者: Mango
本程序旨在将多级链表展成单级链表,方便后续的处理。
使用递归的方法对每一个多级链表节点进行处理,具体过程如下:
class Node {
public:
int val;
Node* prev;
Node* next;
Node* child;
Node(int _val) {
val = _val;
prev = NULL;
next = NULL;
child = NULL;
}
};
class Solution {
public:
Node* flatten(Node* head) {
if (head == NULL) {
return NULL;
}
Node* cur = head;
while (cur != NULL) {
if (cur->child != NULL) {
Node* next = cur->next;
Node* child = flatten(cur->child);
cur->child = NULL;
cur->next = child;
child->prev = cur;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = next;
if (next != NULL) {
next->prev = cur;
}
}
cur = cur->next;
}
return head;
}
};
以上是展平多级链表的 C++ 程序,具体实现参见注释。