[LC] 138. Deep Copy Linked List With Random Pointer

Each of the nodes in the linked list has another pointer pointing to a random node in the list or null. Make a deep copy of the original list.

 

/**
 * class RandomListNode {
 *   public int value;
 *   public RandomListNode next;
 *   public RandomListNode random;
 *   public RandomListNode(int value) {
 *     this.value = value;
 *   }
 * }
 */
public class Solution {
  public RandomListNode copy(RandomListNode head) {
    // Write your solution here.
    if (head == null) {
      return head;
    }
    Map<RandomListNode, RandomListNode> map = new HashMap<>();
    map.put(head, new RandomListNode(head.value));
    RandomListNode dummy = new RandomListNode(0);
    RandomListNode cur = dummy;

    while (head != null) {
      if (!map.containsKey(head)) {
        map.put(head, new RandomListNode(head.value));
      }
      // connect for the next of cur
      cur.next = map.get(head);
      if (head.random != null) {
        if (!map.containsKey(head.random)) {
          map.put(head.random, new RandomListNode(head.random.value));
        }
        cur.next.random = map.get(head.random);
      }
      head = head.next;
      cur = cur.next;
    }
    return dummy.next;
  }
}

 

posted @ 2020-02-26 11:40  xuan_abc  阅读(163)  评论(0)    收藏  举报