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;
      }
    }
  • 相关阅读:
    PHP学习当中遗漏的知识点
    sql必知必会(第四版) 学习笔记
    servlet 笔记
    sql server 快捷键
    233
    第 四 课 数据类型
    第三课 go语言基础语法
    第二课 go语言的结构
    第 1 课 Go 简介
    linux 学习 查看文件占用空间大小
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12365965.html
Copyright © 2011-2022 走看看