剑指offer

面试题35. 复杂链表的复制

2020-03-18  本文已影响0人  人一己千

题目

请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。

示例 1:

image.png

输入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
输出:[[7,null],[13,0],[11,4],[10,2],[1,0]]
示例 2:

image.png

输入:head = [[1,1],[2,1]]
输出:[[1,1],[2,1]]
示例 3:

输入:head = [[3,null],[3,0],[3,null]]
输出:[[3,null],[3,0],[3,null]]
示例 4:

输入:head = []
输出:[]
解释:给定的链表为空(空指针),因此返回 null。

提示:

-10000 <= Node.val <= 10000
Node.random 为空(null)或指向链表中的节点。
节点数目不超过 1000 。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/fu-za-lian-biao-de-fu-zhi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法

先复制next,再复制random。
由于random可能指向任意位置,所以在复制next的时候,顺便把 源节点-->复制节点 的映射保存下来。

class Solution:
    def copyRandomList(self, head: 'Node') -> 'Node':
        if head is None: return
        table = {}
        pHead = Node(head.val)
        result = pHead
        head1 = head
        
        while head :
            table[head] = pHead
            pHead.next = Node(head.next.val) if head.next else None
            head = head.next
            pHead = pHead.next
        pHead = result
        while head1:  
            pHead.random = table[head1.random] if head1.random else None
            pHead = pHead.next
            head1 = head1.next
        return result

总结

哈希表里面的映射是节点到节点的。
while循环里两个的next都要写。
if else None 的写法。
每个链表都要保存两个头结点不被破坏。

上一篇下一篇

猜你喜欢

热点阅读