链表Flattening(扁平化)和Unflattening(还原)

List Flattening:

如下图的doubly linked list, 链表还有一个额外的child指针。现在要将这种hierarchy的链表变成扁平化的只有一层的链表。order不限。我最开始的想法是吧child插入father的后面,虽然这样也可以实现,但是实现起来还是有点麻烦的。而换一角度,从前到后扫描,每次遇到有child的节点,将child接到最后,等到第一层扫描完,第二层的所有节点都接到了第一层后面,正好继续扫描第二层,做法和第一层一样,将第二层的所有child节点接到后面。这样一直到扫描到tail就完毕了。不需要额外空间,时间复杂度是O(n)。

Start at the beginning of the first level
While you are not at the end of the first level
    If the current node has a child
        Append the child to the end of the first level
        Update the tail pointer
    Advance to next node



下图是flattening之后的结果



然后我们考虑逆操作unflattening,从4-4得到4-3。 一样的我们可以按照上面的方法的从前到后扫描,遇到5有child,那么将它的child (6)从前一个节点断开,这样第一层和第二层就分开了。然后一样的方法递归拆开子节点的。拆完后继续走,33,17都没有child,遇到2,把2的子节点2拆开。一直到走到链表结尾,因为6已经被拆开了,1就是结尾了。


Explore path:

While not at the end
    If current node has a child
        Separate the child from its previous node
        Explore path beginning with the child
    Go onto the next node


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值