138. 复制带随机指针的链表_面试题35. 复杂链表的复制

问题

在这里插入图片描述

例子

在这里插入图片描述

思路
直接遍历结点的话,因为random是随机的,有没有创建不知道,所以使用辅助map,旧结点,新结点【遍历结点,复制一份,并放在map中与原结点进行映射】,则原结点之间的映射关系,就是新节点之间的映射关系

  • 方法1
    $$

    $$

  • 方法2
    $$

    $$

代码

//方法1
/*
// Definition for a Node.
class Node {
    int val;
    Node next;
    Node random;

    public Node(int val) {
        this.val = val;
        this.next = null;
        this.random = null;
    }
}
*/
class Solution {
    public Node copyRandomList(Node head) {
        if(head==null) return null;
        Map<Node,Node> map = new HashMap<>();
        
        Node node = head;
        while(node!=null) {
            map.put(node,new Node(node.val));
            node = node.next;
        }
        
        node=head;
        while(node!=null) {
            map.get(node).next = map.get(node.next);
            map.get(node).random = map.get(node.random);
            node=node.next;
        }
        return map.get(head);
        
        
    }
}
//方法2

发布了234 篇原创文章 · 获赞 9 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/puspos/article/details/105266109