Advertisement
ogv

Untitled

ogv
Oct 14th, 2019
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.98 KB | None | 0 0
  1. // Runtime: 0 ms, faster than 100.00% of Java online submissions for Flatten a Multilevel Doubly Linked List.
  2. class Solution {
  3.     public Node flatten(Node head) {
  4.         if (head != null) flatten(head, null);
  5.         return head;
  6.     }    
  7.    
  8.     private void flatten(Node head, Node rest) {
  9.         Node c = head;
  10.         Node tail = null;
  11.                
  12.         while (c != null && c.child == null) {
  13.             tail = c;
  14.             c = c.next;        
  15.         }
  16.          
  17.         if (c == null) {
  18.             link(tail, rest);
  19.             return;
  20.         }                        
  21.                        
  22.         if (c.next != null) {
  23.             flatten(c.next, rest);
  24.             rest = c.next;            
  25.         }
  26.        
  27.         flatten(c.child, rest);        
  28.         link(c, c.child);
  29.         c.child = null;
  30.     }
  31.    
  32.     private void link(Node node, Node next) {
  33.         node.next = next;
  34.         if (next != null) next.prev = node;
  35.     }
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement