Leetcode 430

这个的话套一个递归的模型就好了。

遍历链表,如果遇到了有child 的节点,就用一个函数去将其拉直,并获得其尾部节点的指针。

自己做的时候忘了考虑一些边界条件。空链表的时候不应该处理而应该直接返回,链表长度为1的时候也应当注意判断条件。

class Solution:
    def flatten(self, head: 'Node') -> 'Node':
        def process(head):
            # flatten, but return the last node
            while head:
                if head.child:
                    last = process(head.child)
                    headnext = head.next
                    head.next = head.child
                    head.child.prev = head
                    if headnext:
                        headnext.prev = last
                        last.next = headnext
                    head.child = None
                if head.next:
                    head = head.next
                else:
                    break
            return head
        process(head)
        return head

 

posted on 2021-09-24 18:45  Ricochet!  阅读(24)  评论(0编辑  收藏  举报