解题思路
1)第一次遍历构建完整节点 map.put(cur,newNode); 2)第二次遍历填充它的random指针和next指针 1、 找Y 对应Key—value map.get(X)在 2、在value中设置这个节点的next,和random指针 a) 找指向X 在原链表中查找Y(7)的next值X(13) b) 找X对应key—value 通过原链表map.get(X)在value中寻找对应的X c) 连接,在value中将Y(7).next=map.get(X)
class Solution {
public Node copyRandomList(Node head) {
}
}
class Solution {
public Node copyRandomList(Node head) {
if(head == null ) return null;
Node cur = head;
Map<Node,Node> map = new HashMap<>();
while( cur != null){
Node newNode = new Node(cur.val);
map.put(cur,newNode);
cur = cur.next;
}
cur = head;
while( cur != null){
Node valueCur = map.get(cur);
Node keyNextNode = cur.next;
Node valueNextNode = map.get(keyNextNode);
valueCur.next = valueNextNode;
Node keyRandomNode = cur.random;
Node valueRandomNode = map.get(keyRandomNode);
valueCur.random = valueRandomNode;
cur = cur.next;
}
return map.get(head);
}
}
|