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

[Leetcode LCR 154][Medium]-复杂链表的复制-链表

目录

一、题目描述

二、整体思路

三、代码


一、题目描述

原题地址

二、整体思路

        这道题难点在于如何处理random。因为涉及到的所有节点都在同一链表,因此可以在链表上利用复制-拆分的方法去做。

        先在链表上把每个节点复制自身一次,相当于cur与cur.next中间插入一个val与cur.val相同的新节点。

        然后再复制random,从头遍历链表,cur.next是复制的新节点,cur.next.random=cur.random.next。遍历完的同时random也复制好了。注意不能cur.next.random=cur.random。因为这样的话就拆分不了链表了。

        最后再拆分链表。

三、代码

/*
// 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) {
        if(head==null){
            return null;
        }
        Node cur=head;//复制节点(只复制next)
        while(cur!=null){
            Node nxt=cur.next;
            cur.next=new Node(cur.val);
            cur.next.next=nxt;
            cur=nxt;
        }
        cur=head;
        while(cur!=null){//复制random
            cur.next.random=cur.random==null ? null : cur.random.next;
            cur=cur.next.next;
        }
        cur=head;
        Node res=cur.next;//拆分
        Node temp=res;
        while(cur!=null){
            cur.next=cur.next==null ? null : cur.next.next;
            temp.next=temp.next==null ? null :temp.next.next;
            cur=cur.next;
            temp=temp.next;
        }
        return res;
    }
}


http://www.kler.cn/news/307570.html

相关文章:

  • JSON数组
  • 通信工程学习:什么是接入网(AN)中的CF核心功能
  • dplyr、tidyverse和ggplot2初探
  • 一些学习three的小记录
  • RK3588九鼎创展方案在Arm集群服务器的项目中的应用分析​​
  • 关于决策树集成的一份介绍
  • IDEA 新版本设置菜单展开
  • Python 单元测试详解:Unittest 框架的应用与最佳实践
  • java.人机猜拳游戏
  • JVM 性能优化与调优-Shenandoah GC
  • [K8S]Forbidden: pod updates may not change fields other than
  • 【Linux】NAT
  • 医学数据分析实训 项目三 关联规则分析预备项目---购物车分析
  • Django——多apps目录情况下的app注册
  • 在Ubuntu 16.04上安装R的方法
  • 题目:单调栈
  • SpringBoot用kafka.listener监听接受Kafka消息
  • 基于SpringBoot+Vue+MySQL的美术馆管理系统
  • 基于MySQL 8.0.39的高性能优化版将于10月份开源
  • 15. 三数之和(实际是双指针类型的题目)
  • 记一次实战中对fastjson waf的绕过
  • Python Pickle 与 JSON 序列化详解:存储、反序列化与对比
  • 管家婆云辉煌手机端怎么连接蓝牙打印机?
  • [C++]spdlog学习
  • ubuntu安装mysql 8.0忘记root初始密码,如何重新修改密码
  • 157-安全开发-Python 自动化挖掘项目SRC 目标FOFA 资产Web 爬虫解析库
  • Spring Boot-定时任务问题
  • 兴趣推送与相似推送逻辑设计
  • 第T1周:Tensorflow实现mnist手写数字识别
  • AI学习指南深度学习篇-RMSprop在深度学习中的应用