扁平化多级双向链表——遍历一遍即可,无需递归

题目链接

思路:

  • 从头开始遍历,每遇到一个有child的节点,就将child的子链表嵌入原链表中即可,直至null。
public Node flatten(Node head) {
    
    
        for (Node cursor = head; cursor != null; cursor = cursor.next) {
    
    
            if (cursor.child != null) {
    
    
                Node child = cursor.child;  //取子节点
                child.prev = cursor;        
                while (child.next != null) child = child.next;  //移动到子节点末尾
                if (cursor.next != null) cursor.next.prev = child;
                child.next = cursor.next;       //将这一小段链表嵌入原链表
                cursor.next = cursor.child;
                cursor.child = null;
            }//重复上述操作,直至null,就连成一个链表了
        }
        return head;
    }

猜你喜欢

转载自blog.csdn.net/qq_43665244/article/details/114241423