当前位置: 首页 > article >正文

力扣——随机链表的复制

题目链接:

链接

题目描述:

在这里插入图片描述
在这里插入图片描述

思路:

思路一

利用map,先把val复制到新的node,再把关系复制到node,
key是旧的node,value是新的node
在这里插入图片描述

思路二

不复制在map里,而是直接复制在链表里,相当于插入一个新的node,插入后就会知道原本节点的next,但是不知道random,所以还需要再遍历一次找到random,最后拆分两个链表

实现代码:

class Solution {
    public Node copyRandomList(Node head) {
        Node cur = head;
        Map<Node,Node> map= new HashMap<>();
        while(cur != null){
            map.put(cur,new Node(cur.val));
            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);
    }
}
class Solution {
    public Node copyRandomList(Node head) {
        if(head==null){
            return head;
        }
        //复制插入
        Node cur = head;
        while(cur != null){
            Node tmp = cur.next;
            cur.next = new Node(cur.val);
            cur.next.next = tmp;
            cur = tmp;
        }
        //找random
        cur = head;
        while(cur != null){
            if(cur.random != null){
                cur.next.random = cur.random.next;
            }
            cur = cur.next.next;
        }
        //拆分
        Node ans = head.next, pre = head;
        cur = head.next;
        while(cur.next != null){
            pre.next = pre.next.next;
            cur.next = cur.next.next;
            pre = pre.next;
            cur = cur.next;
        }
        pre.next = null;
        return ans;
    }
}

http://www.kler.cn/a/585026.html

相关文章:

  • Spring Boot + MyBatis-Plus 项目目录结构
  • 【网络】什么是 IHL(Internet Header Length,首部长度)TTL(Time To Live,生存时间)?
  • TypeScript泛型深度剖析:对比JavaScript的灵活与严谨
  • Linux上位机开发实战(按钮响应)
  • Redis 6.2.7安装配置
  • Apache Tomcat漏洞,对其进行升级
  • 【大模型学习】第十九章 什么是迁移学习
  • Flutter_学习记录_实现列表上下拉加载 +实现加载html的数据
  • 贪心算法简介(greed)
  • IP和TCP抓包实验
  • 电路原理(电容 集成电路NE555)
  • 滑动窗口算法-day11(不定长选做)
  • LLM的准确率评估采用什么方式:准确率评估使用的是 `sklearn.metrics` 模块中的 `accuracy_score` 函数
  • AI学习——深度学习核心技术深度解析
  • 父组件中循环生成多个子组件时,有且只有最后一个子组件的watch对象生效问题及解决办法
  • Vue前端页面实现搜索框的重置
  • vue3 + xlsx 实现导入导出表格,导出动态获取表头和数据
  • [微服务设计]3_如何构建服务
  • golang从入门到做牛马:第二十二篇-Go语言并发:多任务的“协同作战”
  • 详细解析 ListView_GetEditControl()