430. Flatten a Multilevel Doubly Linked List
Basic idea is straight forward:
Start form the
head, move one step each time to the next nodeWhen meet with a node with child, say node
p, follow itschild chainto the end and connect the tail node withp.next, by doing this we merged thechild chainback to themain threadReturn to
pand proceed until find next node with child.Repeat until reach
null
class Solution {
public Node flatten(Node head) {
if( head == null) return head;
// Pointer
Node p = head;
while( p!= null) {
/* CASE 1: if no child, proceed */
if( p.child == null ) {
p = p.next;
continue;
}
/* CASE 2: got child, find the tail of the child and link it to p.next */
Node temp = p.child;
// Find the tail of the child
while( temp.next != null )
temp = temp.next;
// Connect tail with p.next, if it is not null
temp.next = p.next;
if( p.next != null ) p.next.prev = temp;
// Connect p with p.child, and remove p.child
p.next = p.child;
p.child.prev = p;
p.child = null;
}
return head;
}
}Inspired by 114. Flatten Binary Tree to Linked List, using head and tail as parameters in recursive method.
Last updated