zoukankan      html  css  js  c++  java
  • 138. Copy List with Random Pointer


    July-06-2019

    和133一样
    先收集所有的NODE,建立一套新的,此时新的直接没有指针关系。
    遍历新的,通过VAL来找到原来的NODE,看看原来NODE指向哪,就把当前指向新的那个位置。

    public Node copyRandomList(Node head) {
        if (head == null) return null;
        Map<Integer, Node> nodes = new HashMap<>();
        Node temp = head;
        while (temp != null) {
            if (!nodes.containsKey(temp.val)) {
                nodes.put(temp.val, temp);
            }
            temp = temp.next;
        }
        
        Map<Integer, Node> copies = nodes.entrySet().stream().collect(
            Collectors.toMap(
                entry -> entry.getKey(), 
                entry -> new Node(entry.getKey(), null, null)
            ));
    
        
        copies.entrySet().stream().forEach(entry -> {
            int key = entry.getKey();
            Node newNode = entry.getValue();
            Node oldNode = nodes.get(key);
            if (oldNode.next != null) {
                newNode.next = copies.get(oldNode.next.val);
            }
            if (oldNode.random != null) {
                newNode.random = copies.get(oldNode.random.val);
            }
    
        });
        
        return copies.get(head.val);
        
    }
    
    Map<String, Long> result2 = list.stream().collect(
                    Collectors.toMap(Hosting::getName, Hosting::getWebsites));
    
    Map<Integer, String> result3 = list.stream().collect(
                    Collectors.toMap(x -> x.getId(), x -> x.getName()));
    
  • 相关阅读:
    CTK 编译
    MITK 2021.2编译
    执行git add .报错LF will be replaced by CRLF in
    vscode标记“&&”不是此版本中的有效语句分隔符
    vscode prettier插件使用无效
    vscode使用技巧
    kafka及hdfs常用命令
    博客已迁移
    SVM
    逻辑回归
  • 原文地址:https://www.cnblogs.com/reboot329/p/11145369.html
Copyright © 2011-2022 走看看