LeetCode 138: 随机链表的复制

1: 题意

深拷贝一个链表,同时要把每个链表的random指针也要指向新的链表的对应的节点

首先我们先解决一个简单的问题就是如何深拷贝一个最普通的链表

class Solution:
    def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
        ## 生拷贝
        head2 = Node(head.val)
        cur = head.next
        cur2 = head2
        while cur!= None:
            cur2.next = Node(cur.val)
            cur = cur.next
            cur2 = cur2.next
        return head2

然后思考我们怎么把random弄到对的链表,我们可以用map记录一下每个链表节点对应的新的链表节点是哪个,然后我们再次遍历原链表然后我们再赋值random

"""
# 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: 'Optional[Node]') -> 'Optional[Node]':
        ## 生拷贝
        if head == None: return None
        head2 = Node(head.val)
        cur = head.next
        cur2 = head2
        map = {head : head2}
        while cur!= None:
            newNode = Node(cur.val)
            map [cur] = newNode
            cur2.next = newNode
            cur = cur.next
            cur2 = cur2.next
        print(1)
        cur = head
        cur2 = head2
        while cur != None:
            random1 = cur.random
            if random1 != None:
                cur2.random = map[random1]
            cur = cur.next
            cur2 = cur2.next

        return head2
        

时间复杂度: O(n)

空间复杂度:O (n)

优化:

这个思路非常巧妙,就是我们先直接在原链表复制一个节点放在源节点后面

"""
# 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: 'Optional[Node]') -> 'Optional[Node]':
        if head is None:
            return None
        cur = head
        while cur:
            cur.next = Node(cur.val, cur.next)
            cur = cur.next.next
        cur = head
        while cur:
            if cur.random:
                cur.next.random = cur.random.next
            cur = cur.next.next

        cur = head.next
        while cur.next:
            cur.next = cur.next.next
            cur = cur.next
        return head.next

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值