剑指 Offer 35. 复杂链表的复制(链表、递归)

题目描述
官方解法

方法一:回溯 + 哈希表

本题要求我们对一个特殊的链表进行深拷贝。如果是普通链表,我们可以直接按照遍历的顺序创建链表节点。而本题中因为随机指针的存在,当我们拷贝节点时,「当前节点的随机指针指向的节点」可能还没创建,因此我们需要变换思路。一个可行方案是,我们利用回溯的方式,让每个节点的拷贝操作相互独立。对于当前节点,我们首先要进行拷贝,然后我们进行「当前节点的后继节点」和「当前节点的随机指针指向的节点」拷贝,拷贝完成后将创建的新节点的指针返回,即可完成当前节点的两指针的赋值。

具体地,我们用哈希表记录每一个节点对应新节点的创建情况。遍历该链表的过程中,我们检查「当前节点的后继节点」和「当前节点的随机指针指向的节点」的创建情况。如果这两个节点中的任何一个节点的新节点没有被创建,我们都立刻递归地进行创建。当我们拷贝完成,回溯到当前层时,我们即可完成当前节点的指针赋值。注意一个节点可能被多个其他节点指向,因此我们可能递归地多次尝试拷贝某个节点,为了防止重复拷贝,我们需要首先检查当前节点是否被拷贝过,如果已经拷贝过,我们可以直接从哈希表中取出拷贝后的节点的指针并返回即可。

在实际代码中,我们需要特别判断给定节点为空节点的情况。

"""
# Definition for a Node.
class Node:
    def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
        self.val = int(x)
        self.next = next
        self.random = random
"""
class Solution:
    def __init__(self):
        self.Node_dict = {}     # 用于保存节点对应关系的字典:{head: new_head}
    def copyRandomList(self, head: 'Node') -> 'Node':
        if head is None:
            return None
        # 若当前节点未被创建
        if head not in self.Node_dict:
            # 创建节点
            new_head = Node(head.val)
            self.Node_dict[head] = new_head
            new_head.next = self.copyRandomList(head.next)
            new_head.random = self.copyRandomList(head.random)
        return self.Node_dict[head]

在这里插入图片描述
在这里插入图片描述

方法二:迭代 + 节点拆分

思路及算法

注意到方法一需要使用哈希表记录每一个节点对应新节点的创建情况,而我们可以使用一个小技巧来省去哈希表的空间。

我们首先将该链表中每一个节点拆分为两个相连的节点,例如对于链表A→B→C,我们可以将其拆分为 A → \rightarrow A’ → \rightarrow B → \rightarrow B’ → \rightarrow C → \rightarrow C’。对于任意一个原节点 S,其拷贝节点 S’即为其后继节点。

这样,我们可以直接找到每一个拷贝节点 S’的随机指针应当指向的节点,即为其原节点 S 的随机指针指向的节点 T 的后继节点 T’。需要注意原节点的随机指针可能为空,我们需要特别判断这种情况。

当我们完成了拷贝节点的随机指针的赋值,我们只需要将这个链表按照原节点与拷贝节点的种类进行拆分即可,只需要遍历一次。同样需要注意最后一个拷贝节点的后继节点为空,我们需要特别判断这种情况。

自己参照官方解法文字写的:

"""
# Definition for a Node.
class Node:
    def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
        self.val = int(x)
        self.next = next
        self.random = random
"""
class Solution:
    def copyRandomList(self, head: 'Node') -> 'Node':
        if head is None:
            return head
        head = self.copy_node(head)
        head = self.change_random(head)
        new_head = self.change_next(head.next)
        return new_head

    def copy_node(self, head: 'Node') -> 'Node':
        """创建复制节点,将每个节点的next节点指向复制节点,并将复制节点的next节点指向原节点的next节点
        
        返回值: 原节点head
        """

        if head is None:
            return None
        copy_head = Node(head.val)
        copy_head.next = self.copy_node(head.next)
        head.next = copy_head
        return head

    def change_random(self, head: 'Node') -> 'Node':
        """修改复制节点指向的随机节点,即将每个复制节点的随机节点指向原节点的随机节点的下一个节点

        返回值: 原节点head
        """

        if head is None or head.next is None:
            return head
        if head.random is None:
            head.next.random = None
        else:
            head.next.random = head.random.next
        head.next.next = self.change_random(head.next.next)
        return head

    def change_next(self, head: 'Node') -> 'Node':
        """修改复制节点的next节点为下一个复制节点

        返回值: 新的new_head节点
        """

        if head is None or head.next is None:
            return head
        head.next = head.next.next
        head.next = self.change_next(head.next)
        return head

在这里插入图片描述

在这里插入图片描述
参照官方代码写的

"""
# Definition for a Node.
class Node:
    def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
        self.val = int(x)
        self.next = next
        self.random = random
"""
class Solution:
    def copyRandomList(self, head: 'Node') -> 'Node':
        if head is None:
            return None
        # 第一次遍历,生成复制节点
        node = head
        while node:
            new_node = Node(node.val)
            new_node.next = node.next
            node.next = new_node
            node = new_node.next

        # 第二次遍历,修改random节点
        node = head
        while node and node.next:
            if node.random is None:
                node.next.random = None
            else:
                node.next.random = node.random.next
            node = node.next.next

        # 第三次遍历,修改next节点
        new_head = head.next
        node = new_head
        while node and node.next:
            node.next = node.next.next
            node = node.next

        return new_head

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值