leetcode138. 复制带随机指针的链表

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_36811967/article/details/88735935

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

要求返回这个链表的深拷贝。
示例:
输入:
{“KaTeX parse error: Expected '}', got 'EOF' at end of input: …":"1","next":{"id”:“2”,“next”:null,“random”:{“KaTeX parse error: Expected 'EOF', got '}' at position 9: ref":"2"}̲,"val":2},"rand…ref”:“2”},“val”:1}
解释:
节点 1 的值是 1,它的下一个指针和随机指针都指向节点 2 。
节点 2 的值是 2,它的下一个指针指向 null,随机指针指向它自己。
提示:
你必须返回给定头的拷贝作为对克隆列表的引用。

先复制主节点,再复制next和random,复制+复制+拆分的方法见剑指offer25.复杂链表的复制

# Definition for singly-linked list with a random pointer.
# class RandomListNode(object):
#     def __init__(self, x):
#         self.label = x
#         self.next = None
#         self.random = None

class Solution(object):
    def copyRandomList(self, head):
        """
        :type head: RandomListNode
        :rtype: RandomListNode
        """
        if not head:
            return None
        res, a, b = {}, head, head
        while a:  # 先复制主节点
            res[a] = Node(a.val, None, None)
            a = a.next
        while b:  # 再复制next和random
            res[b].next = res.get(b.next)
            res[b].random = res.get(b.random)
            b = b.next
        return res[head]

猜你喜欢

转载自blog.csdn.net/sinat_36811967/article/details/88735935