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;
      }
    }
  • 相关阅读:
    引领5G行业化,广和通荣获“IoT创新大奖”
    Win知识
    物联网通信方式
    萌新配置rip动态路由实验
    FPGA设计经验总结
    UWB定位技术
    REST简介
    linux性能调优总结
    Nginx安装及启动
    leetcode 精选top面试题
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12365965.html
Copyright © 2011-2022 走看看