You seem to have created duplicate nodes for the sake of random pointers


#1

public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {
RandomListNode str=head;
while(head.next!=null){
RandomListNode x= new RandomListNode(head.label);
x.next=head.next;
x.random=head.random;
head.next=x;
head=x.next;
// x=head.next;
}
head=str;
// head=head.next;
while(head.random.next!=null){
head.next.random=head.random.next;
head=head.next.next;
}

head=str;
// head= head.next;
while(head.next.next.next!=null){
    head.next.next=head.next.next.next;
    head=head.next;
}
return str.next;
}

}

I dont understand what is going wrong, Answer is right but this statement is comming again and again “You seem to have created duplicate nodes for the sake of random pointers.”


#2

I am facing the same problem, did you understand the mistake?


#3

I am also facing the same error for the below solution. Anyone know the reason?

Solution:

public RandomListNode copyRandomList(RandomListNode head) {
    if(head == null){
        return head;
    }
    
    Map<RandomListNode,RandomListNode> map = new HashMap<>();
    
    RandomListNode tmp = head;
    
    while(tmp != null){
        map.put(tmp,new RandomListNode(tmp.label));
        tmp = tmp.next;
    }
    
    tmp = head;
    
    while(tmp != null){
        map.get(tmp).random = map.get(tmp.random);
        tmp = tmp.next;
    }
    
    return map.get(head);
}