链表|138. 随机链表的复制

题目: 给你一个长度为 n 的链表,每个节点包含一个额外增加的随机指针 random ,该指针可以指向链表中的任何节点或空节点。
构造这个链表的 深拷贝。 深拷贝应该正好由 n 个 全新 节点组成,其中每个新节点的值都设为其对应的原节点的值。新节点的 next 指针和 random 指针也都应指向复制链表中的新节点,并使原链表和复制链表中的这些指针能够表示相同的链表状态。复制链表中的指针都不应指向原链表中的节点 。
例如,如果原链表中有 X 和 Y 两个节点,其中 X.random --> Y 。那么在复制链表中对应的两个节点 x 和 y ,同样有 x.random --> y 。
返回复制链表的头节点。
题目链接: 138. 随机链表的复制
解题思路:
基本思路:1.第一遍先复制原本的node节点 并使用map存储两者的对应关系
2.第二遍map 给新节点加上next和random关系

/*
// 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) {
        HashMap<Node,Node> map=new HashMap<>();
        Node oldPoint=head;
        //复制链表 放入hash
        while(oldPoint!=null){
            Node newNode=new Node(oldPoint.val);
            map.put(oldPoint,newNode);
            oldPoint=oldPoint.next;
        } 
        //遍历Map 创建next和Random关系 
        oldPoint=head;
        while(oldPoint!=null){
            //map.get(oldPoint)为新节点
            //通过找到oldPoint.next找到其对应的新节点
            map.get(oldPoint).next=map.get(oldPoint.next);
            map.get(oldPoint).random=map.get(oldPoint.random);
            oldPoint=oldPoint.next;
        }
        return map.get(head); 
    }
}

你可能感兴趣的:(代码随想录,链表,数据结构)