138. 随机链表的复制

随机链表复制方法解析

原题

https://leetcode.cn/problems/copy-list-with-random-pointer/description/

思路

字典

复杂度

时间:O(n)
空间:O(n)

Python代码

"""
# 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 not head:
            return None
        dic = dict()
        cur = head 
        while cur:
            node = Node(cur.val)
            dic[cur] = node
            cur = cur.next 
        cur = head 
        while cur:
            node = dic[cur]
            node.next = dic.get(cur.next)
            node.random = dic.get(cur.random)
            cur = cur.next 
        return dic[head]
        

Go代码

/**
 * Definition for a Node.
 * type Node struct {
 *     Val int
 *     Next *Node
 *     Random *Node
 * }
 */

func copyRandomList(head *Node) *Node {
	if head == nil {
		return nil
	}
	// 字典存储原节点和复制的节点
	m := map[*Node]*Node{}
	cur := head
	for cur != nil {
		node := &Node{Val: cur.Val}
		m[cur] = node
		cur = cur.Next
	}
	cur = head
	for cur != nil {
		node := m[cur]
		node.Next = m[cur.Next]
		node.Random = m[cur.Random]
		cur = cur.Next
	}
	return m[head]
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值