Java 10 lines solution without any collections in O(n)


  • 0
    H
    public class Solution {
        public RandomListNode copyRandomList(RandomListNode head) {
            RandomListNode copyHead;
            if(head==null) return null;
            RandomListNode copy=new RandomListNode(head.label);
            copyHead=copy;
            do
            {
                copy.next=(head.next==null?null:new RandomListNode(head.next.label));
                copy.random=(head.random==null?null:new RandomListNode(head.random.label));
                copy=copy.next;
                head=head.next;
            }while(head!=null);
            return copyHead;
        }
    }
    

Log in to reply
 

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