【hot100-java】随机链表的复制
链表篇
/*
// 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;}java.util.Map<Node,Node>dict=new java.util.HashMap<>();Node cur=head;//复制各节点,建立"key-value"的map映射while (cur!=null){dict.put(cur,new Node(cur.val));cur=cur.next;}cur=head;//构建next和random指向while(cur!=null){dict.get(cur).next=dict.get(cur.next);dict.get(cur).random=dict.get(cur.random);cur=cur.next;}//返回新链表的头结点return dict.get(head); }
}