Copy List with Random Pointer


#1

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.


#2

Just does a deep copy of all the nodes. Uses a temporary anchor to keep track of the head of the list.

/**
 * Definition for singly-linked list with a random pointer.
 * class RandomListNode {
 *     int label;
 *     RandomListNode next, random;
 *     RandomListNode(int x) { this.label = x; }
 * };
 */
public class Solution {
    public RandomListNode copyRandomList(RandomListNode head) {
      RandomListNode newHead = new RandomListNode(0);
      RandomListNode anchor = newHead;
      while(head!=null){
         newHead.next = new RandomListNode(head.label);
         newHead = newHead.next;
         if(head.random!=null){
             newHead.random = new RandomListNode(head.random.label);
              newHead.random.next = head.random.next;
         }
         head=head.next;
      }
        return anchor.next;
    }
}