My Java easy solution with HashMap


  • 0
    F

    public class Solution {

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

    }


Log in to reply
 

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