算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 扁平化多级双向链表,我们先来看题面:
https://leetcode-cn.com/problems/flatten-a-multilevel-doubly-linked-list/
You are given a doubly linked list which in addition to the next and previous pointers, it could have a child pointer, which may or may not point to a separate doubly linked list. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure, as shown in the example below.
Flatten the list so that all the nodes appear in a single-level, doubly linked list. You are given the head of the first level of the list.
多级双向链表中,除了指向下一个节点和前一个节点指针之外,它还有一个子链表指针,可能指向单独的双向链表。这些子列表也可能会有一个或多个自己的子项,依此类推,生成多级数据结构,如下面的示例所示。
给你位于列表第一级的头节点,请你扁平化列表,使所有结点出现在单级双链表中。
示例
解题
思路 :采用DFS,注释都写在代码里了。
class Solution {
public:
Node* flatten(Node* head) {
Node *cur = head, *nextNode = NULL, *prevN = head;
//所有的指针记得初始化,不要以为后面要付值就不要初始值,怕后面if没进去
while(prevN)
{ //遍历链表
if(cur && cur->child) //当前有,且有子链
{
nextNode = cur->next;//记住上层cur后面的
cur->next = flatten(cur->child);//展平
cur->child->prev = cur;//子链头接上,展平
cur->child = NULL;//将cur孩子删掉
}
prevN = cur;//prevnode移动
if(cur)
cur = cur->next;//cur移动
if(!cur && nextNode)
{ //当cur到终点的下一个时,且上层后面还有nextnode
prevN->next = nextNode;//展平的终点prevN指向上层的nextnode
nextNode->prev = prevN;//反向接上
cur = prevN->next;//cur移动
nextNode = NULL;//已接好,暂时没有child的需要展平,nextNode清空
}
}
return head;
}
};
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。
上期推文:
LeetCode刷题实战426:将二叉搜索树转化为排序的双向链表