您将获得一个双向链表,除了下一个和前一个指针之外,它还有一个子指针,可能指向单独的双向链表。这些子列表可能有一个或多个自己的子项,依此类推,生成多级数据结构,如下面的示例所示。
扁平化列表,使所有结点出现在单级双链表中。您将获得列表第一级的头部。
示例:
输入:
1—2---3—4---5—6–NULL
|
7—8---9—10–NULL
|
11–12–NULL
输出:
1-2-3-7-8-11-12-9-10-4-5-6-NULL
以上示例的说明:
给出以下多级双向链表:

我们应该返回如下所示的扁平双向链表:

思路:
该题用递过来解很方便,某个结点不含有child,那么直接flatten后面的链表post作为next;如果含有child,那么需要先将child给flatten,然后将child跟head和post拼接起来,这儿需要注意post若为NULL,那么不需要指定NULL的prev的,故指定post的prev之前需要判断是够为NULL。
/*
// Definition for a Node.
class Node {
public:
int val;
Node* prev;
Node* next;
Node* child;
Node() {}
Node(int _val, Node* _prev, Node* _next, Node* _child) {
val = _val;
prev = _prev;
next = _next;
child = _child;
}
};
*/
class Solution {
public:
/*
输入:
1---2---3---4---5---6--NULL
|
7---8---9---10--NULL
|
11--12--NULL
输出:
1-2-3-7-8-11-12-9-10-4-5-6-NULL
*/
Node* flatten(Node* head) {
if (!head) return NULL;
else if (head->child==NULL)
{
head->next=flatten(head->next);
}
else
{
Node* post=flatten(head->next);
Node* child=head->child;
head->child=NULL;
child = flatten(child);
head->next=child;
child->prev=head;
Node* c=child;
while(c->next) c=c->next;
c->next=post;
if (post) post->prev=c;
}
return head;
}
};
621

被折叠的 条评论
为什么被折叠?



