Skip to content

138. 随机链表的复制

📝 题目链接

📷 题目截图

img_3.png

💡 解题思路

不难,主要是理解题目,用Map存,遍历就行。

方法:

📊 代码实现

java
/*
// Definition for a Node.
class Node {
    int val;
    Node next;
    Node random;

    public Node(int val) {
        this.val = val;
        this.next = null;
        this.random = null;
    }
}
*/

class Solution {
    public Node copyRandomList(Node head) {
        Map<Node, Node> map = new HashMap<>();
        Node cur = head;
        while (cur != null) {
            map.put(cur, new Node(cur.val,cur.next,cur.random));
            cur = cur.next;
        }
        Node temp = head;
        while (temp != null) {
            map.get(temp).next = map.get(temp.next);
            map.get(temp).random = map.get(temp.random);
            temp = temp.next;
        }
        return map.get(head);
    }
}

Released under the MIT License.