Advertisement
Guest User

Untitled

a guest
Oct 14th, 2019
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.90 KB | None | 0 0
  1. /*
  2. Runtime: 0 ms, faster than 100.00% of Java online submissions for Flatten a Multilevel Doubly Linked List.
  3. Memory Usage: 37.4 MB, less than 85.00% of Java online submissions for Flatten a Multilevel Doubly Linked List.
  4. */
  5. class Solution {
  6.     public Node flatten(Node head) {
  7.         flatten2(head);
  8.         return head;
  9.     }
  10.    
  11.     private Node flatten2(Node head) {
  12.         while(head != null && head.child == null && head.next != null) head = head.next;
  13.         if (head == null || head.child == null)  {
  14.             return head;
  15.         }
  16.        
  17.         Node trailingTail = head.next;
  18.        
  19.         head.next = head.child;
  20.         head.next.prev = head;
  21.         head.child = null;
  22.        
  23.         head = flatten2(head);
  24.        
  25.         head.next = trailingTail;
  26.         if (head.next != null) {
  27.             head.next.prev = head;
  28.         }
  29.         return flatten2(head);
  30.     }
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement