LeetCode-138.复制带随机指针的链表(相关话题:哈希表)

给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。

要求返回这个链表的深度拷贝。

Java代码:

public class Solution {
    public RandomListNode copyRandomList(RandomListNode head) {
        if (null == head)
            return null;

        RandomListNode p = head.next, result = new RandomListNode(head.label), q = result;
        Map<RandomListNode, RandomListNode> map = new HashMap<>(), link = new HashMap<>();
        link.put(head, result);
        if (null != head.random)
            map.put(head, result);
        while (null != p) {
            RandomListNode tmp = new RandomListNode(p.label);
            q.next = tmp;
            link.put(p, tmp);
            if (null != p.random)
                map.put(p, tmp);
            p = p.next;
            q = q.next;
        }

        for (RandomListNode r : map.keySet()) {
            map.get(r).random = link.get(r.random);
        }

        return result;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_38823568/article/details/87814059