Leetcode 138:复制带随机指针的链表(超详细的解法!!!)

版权声明:本文为博主原创文章,未经博主允许不得转载。有事联系:[email protected] https://blog.csdn.net/qq_17550379/article/details/85775211

给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。

要求返回这个链表的深度拷贝。

解题思路

这个问题其实挺难的,关键问题就在于这个random指针。我们看这样的例子

我们可以这样去做

首先遍历链表,然后将节点复制添加到原节点后。

接着再遍历一遍链表,这一次的遍历我们复制random指针。

最后我们将链表还原回去。代码如下:
class Solution(object):
    def copyRandomList(self, head):
        """
        :type head: RandomListNode
        :rtype: RandomListNode
        """
        if not head:
            return None
        
        h1, h2, h = head, head, head
        while h1:
            node = RandomListNode(h1.label)
            node.next = h1.next 
            h1.next = node
            h1 = node.next
            
        while h2:
            if h2.random:
                h2.next.random = h2.random.next
            h2 = h2.next.next
            
        res = h.next
        while h:
            tmp = h.next
            h.next = tmp.next
            if h.next:
                tmp.next = h.next.next
            h = h.next
            
        return res

我将该问题的其他语言版本添加到了我的GitHub Leetcode

如有问题,希望大家指出!!!

猜你喜欢

转载自blog.csdn.net/qq_17550379/article/details/85775211
今日推荐