// 输入:[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]
// 解释如下:
// 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]
// 解释如下:
// 1---2---3---7---8---11---12---9---10---4---5---6--NULL
head,以如下步骤进行处理:
head->next,将递归返回的节点保存为 tmp。【保存 head->next,准备断开链】head->child,将 head->next 置为递归返回的结果,此时 head->next = head->child,因为是双向链表,所以需要反过来再连接,即 head->next->prev = head。【此时已经处理好 head 和 head->child 的关系,后续就是处理 head 和 tmp 的连接关系】head 为 ret 以便最后返回,即 ret = head。head 此时连接着 head->child,则将 head 向后移动直到走尽,走尽后将尾部与 tmp 连接。ret 作为链表头返回。head 和 head->child、走尽 head、连接 head 和原来的 head->next。class Solution
{
public:
Node* flatten(Node* head)
{
if(!head) return head;
// 递归处理 head->next
Node* tmp = flatten(head->next);
// 递归处理 head->child
head->next = flatten(head->child);
head->child = nullptr;
if(head->next)
head->next->prev = head;
// 保存当前 head 为 ret
Node* ret = head;
// 走尽 head,并连接 head 和 tmp
while(head->next) head = head->next;
head->next = tmp;
if(tmp) tmp->prev = head;
return ret;
}
};