原题地址: https://leetcode-cn.com/probl...
repo地址: https://github.com/pigpigever...
遇到问题咱们首先要先搞清楚问题究竟是什么,而后再想办法解决。对于 链表 的问题其实大部分都不算难,写代码以前最好动动笔在纸上画一下,思路便会清晰不少。javascript
题目中描述这样一个结构的链表:前端
function Node(val,prev,next,child) { this.val = val; this.prev = prev; this.next = next; this.child = child; }
因此这不单单是一个 双向 链表,同时它还可能存在 子链表 java
咱们再来看看官方提供的输入输出例子👇git
输入:github
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
扁平化的步骤能够当作这样:学习
第一步:this
1---2---3---4---5---6--NULL | 7---8---11---12---9---10--NULL
第二步:spa
1---2---3---7---8---11---12---9---10---4---5---6--NULL
显然,咱们须要递归处理 子链表,再把它跟 父链表 拼接在一块儿。指针
分析完题目以后咱们来梳理下逻辑👇
拼接的逻辑能够更加细化,以下👇
/** * @param {Node} head * @return {Node} */ var flatten = function(head) { dfs(head) function dfs (head) { let target = head, pre = null, last = null while (target) { let next = target.next, child = target.child if (child) { target.next = child child.prev = target target.next = child last = dfs(child) last.next = next pre = last target.child = null if (next) { next.prev = last } } else { pre = target } target = next } return pre } return head };
固然这里有个须要注意的地方,next
、 prev
和 child
指针均可能是空的,写代码的时候须要把这些状况都考虑进去。
一直在 LeetCode 上刷题,以前还加入了组织,有兴趣加入一块儿学习的同窗能够在下方留言或者关注个人微信公众号「tony老师的前端补习班」并在后台留言,能够进群跟大佬们一块儿学习。