138. 随机链表的复制

  1. 题目链接

  2. 解题思路:先拷贝新节点,新节点放在老节点后面。然后再遍历一遍,设置新节点的random指针。新节点的random,指向的是「老节点的random的下一个节点」。最后将新老节点分开即可。

  3. 代码

    class Solution:
        def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
            if head == None:
                return None
            # 先将拷贝的节点创建在被拷贝节点后面
            cur = head
            while cur:
                new_node = Node(cur.val, cur.next)
                cur.next = new_node
                cur = new_node.next
            # 复制random指针
            cur = head
            while cur:
                copy_node = cur.next
                if cur.random != None:
                    copy_node.random = cur.random.next
                cur = copy_node.next
            ans = head.next
            # 断开拷贝节点和被拷贝节点的关联
            cur = head
            while cur:
                copy_node = cur.next
                cur.next = copy_node.next
                cur = cur.next
                if cur != None:
                    copy_node.next = cur.next
            return ans
    
posted @ 2024-12-27 14:36  ouyangxx  阅读(9)  评论(0)    收藏  举报