LeetCode 刷题【138. 随机链表的复制】

138. 随机链表的复制

自己做

解:哈希表

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) {
        Node p = head;
        Node res = new Node(0);
        Node q = res;
        List<Node> list = new ArrayList();
        Map<Node, Integer> hash1 = new HashMap();
        int i = 0;

        //根据next复制链表
        while(p != null){
            q.next = new Node(p.val);
            q = q.next;

            hash1.put(p, i);
            list.add(q);
            
            p = p.next;
            i++;
        }

        //建立random
        p = head;
        q = res.next;

        while(p != null){
            if(p.random != null)
                q.random = list.get(hash1.get(p.random));
            else
                q.random = null;

            p = p.next;
            q = q.next;
        }


        return res.next;
    }
}
相关推荐
2301_810160952 分钟前
C++与物联网开发
开发语言·c++·算法
cm6543206 分钟前
基于C++的操作系统开发
开发语言·c++·算法
ArturiaZ8 分钟前
【day57】
开发语言·c++·算法
CoovallyAIHub10 分钟前
Energies | 8版YOLO对8版Transformer实测光伏缺陷检测,RF-DETR-Small综合胜出
深度学习·算法·计算机视觉
Emberone17 分钟前
排序:万物皆有序
算法·排序算法
其实秋天的枫19 分钟前
2025年12月英语六级真题及答案解析完整版(第一、二、三套全PDF)
经验分享·算法
2401_8747325325 分钟前
C++并发编程中的死锁避免
开发语言·c++·算法
2301_7923082527 分钟前
C++编译期数学计算
开发语言·c++·算法
hetao173383728 分钟前
2025-03-13~22 hetao1733837 的刷题记录
c++·算法
sqyno1sky39 分钟前
C++中的契约编程
开发语言·c++·算法