Java iterative solution, no map needed


  • -1
    G
    public RandomListNode copyRandomList(RandomListNode head) {
        if(head==null){
            return head;
        }
        
        RandomListNode newHead = new RandomListNode(head.label);
        RandomListNode  temp = head;
        RandomListNode newTemp = newHead;
        while(temp.next!=null){
            if(temp.next!=null&&newTemp.next==null){
                newTemp.next = new RandomListNode(temp.next.label);
            }
            
            if(temp.random!=null&&newTemp.random==null){
                newTemp.random = new RandomListNode(temp.random.label);
            }
            temp = temp.next;
            newTemp = newTemp.next;
        }
        if(temp.random!=null&&newTemp.random==null){
            newTemp.random = new RandomListNode(temp.random.label);
        }
        return newHead;
    }

Log in to reply
 

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