Simple and Clean Java solution O(1) space O(N) Time.


  • 0
    H
    public RandomListNode copyRandomList(RandomListNode head) {
            // create replica next to original
            RandomListNode temp= head;
            if(temp==null) return null;
            while(temp!=null){
                RandomListNode New= new RandomListNode(temp.label);
                New.next=temp.next;
                temp.next=New;
                temp=New.next;
            }
            
            // copy the random pointer
            temp= head;
            while(temp!=null){
                temp.next.random= (temp.random==null)?null:temp.random.next;
                temp= temp.next.next;
            }
            RandomListNode headCopy=head.next;
            temp=head;
            RandomListNode temp2= headCopy;
            //restore the original back
            
            while(temp!=null && temp2!=null){
                temp.next= temp2.next;
                temp= temp.next;
                temp2.next= (temp==null)?null:temp.next;
                temp2=temp2.next;
            }
            return headCopy;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.