我的题解
/*
// 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;
Node tmp = head,headA,headB;
headA =new Node(head.val);
headB=headA;
while(tmp!=null){//安排好next指针(先让节点连起来)
tmp=tmp.next;
if(tmp==null) break;
Node cur =new Node(tmp.val);
headA.next=cur;
headA=cur;
}
tmp=head;
Node cur=headB;
while(tmp!=null){//安排random指针
//初始化数据
int i=0,j=0;
headA=headB;
Node tmp1=head;
while(tmp1!=null){//双重循环确定每一个节点的random指向的位置(用计数器记录)
if(tmp.random==null){
i=-1;break;
}
i++;
if(tmp.random==tmp1){
break;
}
tmp1=tmp1.next;
}
while(headA!=null){
if(i==-1) break;
j++;
if(i==j){//移动到之前计数的相同位置直接进行指向
cur.random=headA;
break;
}
headA=headA.next;
}
tmp=tmp.next;
cur=cur.next;
}
return headB;
}
}
官方题解
/*
// 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 head;
Map<Node,Node> m = new HashMap<>();
Node cur = head;
while(cur != null){
m.put(cur,new Node(cur.val));
cur = cur.next;
}
cur = head;
while(cur != null){
m.get(cur).next = m.get(cur.next);
m.get(cur).random = m.get(cur.random);
cur = cur.next;
}
return m.get(head);
}
}