138. Copy List with Random Pointer

本文介绍了一种深拷贝含随机指针的单链表算法,通过使用哈希映射来处理节点复制及其随机指针的连接,确保了新链表的独立性和正确性。

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

与图拷贝的方法类似,使用map的方式进行处理,但是也有不同,图拷贝是线拷贝点,然后是边;链表可以直接在一个循环中统一处理。

java

/**
 * Definition for singly-linked list with a random pointer.
 * class RandomListNode {
 *     int label;
 *     RandomListNode next, random;
 *     RandomListNode(int x) { this.label = x; }
 * };
 */
public class Solution {
    public RandomListNode copyRandomList(RandomListNode head) {
        if (head == null) {
            return head;
        }
        Map<RandomListNode, RandomListNode> map = new HashMap<>();
        RandomListNode dummy = new RandomListNode(0);
        RandomListNode pre = dummy;
        RandomListNode node;
        while (head != null) {
            if (map.containsKey(head)) {
                node = map.get(head);
            } else {
                node = new RandomListNode(head.label);
                map.put(head, node);
            }
            pre.next = node;
            if (head.random != null) {
                if (map.containsKey(head.random)) {
                    node.random = map.get(head.random);
                } else {
                    node.random = new RandomListNode(head.random.label);
                    map.put(head.random, node.random);
                } 
            }
            pre = pre.next;
            head = head.next;
        }
        return dummy.next;
    }
}

python

# Definition for singly-linked list with a random pointer.
# class RandomListNode(object):
#     def __init__(self, x):
#         self.label = x
#         self.next = None
#         self.random = None

class Solution(object):
    def copyRandomList(self, head):
        """
        :type head: RandomListNode
        :rtype: RandomListNode
        """
        if head is None:
            return head
        mapping = {}
        dummy = RandomListNode(0)
        pre, node = dummy, head
        while head is not None:
            if head in mapping:
                node = mapping[head]
            else:
                node = RandomListNode(head.label)
                mapping[head] = node
            pre.next = node
            if head.random is not None:
                if head.random in mapping:
                    node.random = mapping[head.random]
                else:
                    node.random = RandomListNode(head.random.label)
                    mapping[head.random] = node.random
            pre = pre.next
            head = head.next
        return dummy.next


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ncst

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值