🌕 430. 扁平化多级双向链表

吞佛童子2022年10月10日
  • algorithm
  • list
小于 1 分钟

🌕 430. 扁平化多级双向链表

难度: 🌕

问题描述

img_1.png


解法

/*
// Definition for a Node.
class Node {
    public int val;
    public Node prev;
    public Node next;
    public Node child;
};
*/

class Solution {
    public Node flatten(Node head) {
        // 思路:
        // 递归
        Node[] res = mySol(head);
        return res[0];
    }

    private Node[] mySol(Node head) {
        Node[] res = new Node[2];
        
        Node cur = head;
        Node p = null;
        while(cur != null) {
            // System.out.println(cur.val);
            if(cur.child != null) {
                Node next =cur.next;

                Node[] c = mySol(cur.child);  
                cur.child = null;             
                cur.next = c[0];
                c[0].prev = cur;
                c[1].next = next;
                if(next != null) {
                    next.prev = c[1];
                }
                cur = next;
                p = c[1];
            } else {
                p = cur;
                cur = cur.next;
            }
        }
        res[0] = head;
        res[1] = p;
        return res;
    }
}

输出

img.png

上次编辑于: 2022/10/10 下午8:43:48
贡献者: liuxianzhishou