Timi Areola's Java Solution


  • 0
    T

    public class Solution {
    public RandomListNode copyRandomList(RandomListNode head) {
    RandomListNode curr = head, next;

        //create duplicate nodes and follow original nodes immediately
        while(curr != null)
        {
            //store next node
            next = curr.next;
            
            //create duplicate of current node and immediately follow the current node
            RandomListNode copy = new RandomListNode(curr.label);
            curr.next = copy;
            copy.next = next;
            
            //move to next 'original' node
            curr = next;
        }
        
        curr = head;
        
        //assign random pointers to the duplicate nodes
        while(curr != null)
        {
            //check if random pointer is null, if not, assign random duplicate pointers
            if(curr.random != null)
            {
                curr.next.random = curr.random.next;
            }
            
            curr = curr.next.next;
        }
        
        curr = head;
        RandomListNode dupHead = new RandomListNode(0);
        RandomListNode copy, dupCurrent = dupHead;
        //seperate the original list from duplicate list
        while(curr != null)
        {
            //get duplicates
            copy = curr.next;
            dupCurrent.next = copy;
            dupCurrent = dupCurrent.next;
            
            //restore original list
            curr.next = curr.next.next;
            
            curr = curr.next;
        }
        
        return dupHead.next;
    }
    

    }


Log in to reply
 

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