Advertisement
K_S_

Untitled

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