zoukankan      html  css  js  c++  java
  • [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;
      }
    }
  • 相关阅读:
    关系数据理论
    JavaScript语言——对象
    网络编程基础入门级
    数据库加快查询速度索引
    C/C++随机函数的生成(转载)
    sql连接查询
    深入浅出HTTP请求
    17搜索如何抓全网页
    搜索引擎之百度一下
    搜索引擎之中搜
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12365965.html
Copyright © 2011-2022 走看看