Advertisement
jinhuang1102

430. Flatten a Multilevel Doubly Linked List

Jan 14th, 2019
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.46 KB | None | 0 0
  1. """
  2. Basic idea is straight forward:
  3.  
  4. 1. Start form the head , move one step each time to the next node
  5. 2. When meet with a node with child, say node p, follow its child chain to the end and connect the tail node with p.next, by doing this 3. we merged the child chain back to the main thread
  6. 4. Return to p and proceed until find next node with child.
  7. 5. Repeat until reach null
  8. """
  9. class Solution:
  10.     def flatten(self, head):
  11.         """
  12.        :type head: Node
  13.        :rtype: Node
  14.        """
  15.         if not head:
  16.             return None
  17.        
  18.         tmp = head
  19.         while tmp:
  20.             # if got a child:
  21.             if tmp.child:
  22.                 tmp2 = tmp.child
  23.                
  24.                 # find the tail of the child
  25.                 while tmp2.next:
  26.                     tmp2 = tmp2.next
  27.                    
  28.                 # link it to tmp.next
  29.                 tmp2.next = tmp.next
  30.                
  31.                 # if tmp.next not None, connect the tmp.next.prev to the tail of the children list
  32.                 if tmp.next:
  33.                     tmp.next.prev = tmp2
  34.                    
  35.                 # connect the children list to ancestor list and None the child
  36.                 tmp.next = tmp.child
  37.                 tmp.child.prev = tmp
  38.                 tmp.child = None
  39.                
  40.             # if doesn't got child, go to the next
  41.             else:
  42.                 tmp = tmp.next
  43.                
  44.         return head
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement