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()));
    
  • 相关阅读:
    SCCM2012 R2实战系列之四:初始化配置
    SCCM 2012 R2实战系列之一:SQL安装
    hdu 1242(bfs)
    hdu 1728(bfs)
    hdu 1253(bfs)
    hdu 3661
    hdu 1072(bfs)
    AC模版
    hdu 1010(dfs)
    poj 3628(01_page, dfs)
  • 原文地址:https://www.cnblogs.com/reboot329/p/11145369.html
Copyright © 2011-2022 走看看