Clean Java solution


  • 0
    L
        public RandomListNode copyRandomList(RandomListNode head) {
            if(head==null) {
                return null;
            }
            
            RandomListNode node = head;
            //pass 1.
            while(node!=null) {
               RandomListNode next = node.next;
               node.next = new RandomListNode(node.label);
               node.next.next = next;
               node = next;
            }
    
            
            //pass 2.
            node = head;
            while(node!=null && node.next!=null) {
                if(node.random!=null) {
                    node.next.random = node.random.next;
                }
                node = node.next.next;
            }
            
            //pass 3.
            RandomListNode orig = head;
            RandomListNode ret = head.next;
            node = ret;
            while(node!=null && node.next!=null ) {
                orig.next = node.next;
                orig = orig.next;
                node.next = node.next.next;
                node = node.next;
            }
            orig.next=null;
            return ret;
    

Log in to reply
 

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