原題地址: 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老師的前端補習班」並在後臺留言,能夠進羣跟大佬們一塊兒學習。