拷贝带随机指针的链表

思路:利用map存储节点之间的对应关系

public class DeepCopyLinkedList {

    
    public static void main(String[] args) {

        Node node1 = new Node(1);
        node1.next = new Node(2);
        node1.next.next = new Node(5);
        node1.next.next.next = new Node(7);
        node1.next.next.random = node1.next; // 设置5的random指向2
        node1.next.next.next.next = new Node(8);
        node1.next.next.next.random = node1; // 设置 7的random指向 1
        display(node1);

        Node node2 = deepCopy(node1);
        display(node2);

    }

    /**
     * 第一次遍历,生成新的节点,将当前节点和对应的新节点保存在map中  , 第二次遍历,同时给next和random赋值
     */
    public static Node deepCopy2(Node head) {
        HashMap<Node, Node> map = new HashMap<Node, Node>();
        Node cur = head;
        while (cur != null) {
            map.put(cur, new Node(cur.value));
            cur = cur.next;
        }
        cur = head;
        while (cur != null) {
            map.get(cur).next = map.get(cur.next);
            map.get(cur).random = map.get(cur.random);
            cur = cur.next;
        }
        return map.get(head);
    }

    /**
     * 
     * 第一次遍历,生成新的节点,给next赋值,将节点连接起来,将当前节点和对应的新节点保存在map中 ,  第二次遍历,给random赋值,
     */
    public static Node deepCopy(Node head) {
        Node node1 = head;
        Map<Node, Node> map = new HashMap<Node, Node>();
        Node res = null;
        // 第一次遍历,只是拷贝next节点
        Node newHead = null;
        while (head != null) {
            Node temp = new Node(head.value);
            if (newHead == null) {
                newHead = temp;
                res = temp;
            } else {
                newHead.next = temp;
                newHead = temp;
            }
            // 将当前节点作为key,新生成的节点作为value,存入map中
            map.put(head, temp);
            head = head.next;
        }
        // 第二次遍历时,设置random的值
        Node node3 = res;
        while (node1 != null && node3 != null) {
            node3.random = map.get(node1.random);
            node1 = node1.next;
            node3 = node3.next;
        }
        return res;
    }

    public static void display(Node head) {
        StringBuilder sb = new StringBuilder();
        while (head != null) {
            sb.append(" ( " + head.value + " , " + (head.random == null ? "null" : head.random.value) + " )" + " -> ");
            head = head.next;
        }
        String res = sb.substring(0, sb.lastIndexOf(" -> "));
        System.out.println(res);
    }

    public static class Node {

        Node next;
        Node random;
        int value;

        public Node(int value) {
            super();
            this.value = value;
        }
    }
}
原文地址:https://www.cnblogs.com/moris5013/p/11646837.html