复制带随机指针的链表

简介: 复制带随机指针的链表

image.png


本题目一共有两种解决方法,一种是使用HashMap存储键值对,另一种方法是原地复制;

解法一:使用HashMap存储键值对


/*
// 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;
    }
}
*/
//第一种方法使用HashMap方法方法
class Solution {
    public Node copyRandomList(Node head) {
        if(head==null){
            return null;
        }
        //将节点复制到到键值对中
        Node node=head;
        Map<Node,Node> map=new HashMap<>(); 
        while(node!=null){
            Node clone=new Node(node.val);
            map.put(node,clone);
            node=node.next;
        }
        node=head;
        //复制随机域
        while(node!=null){
            map.get(node).next=map.get(node.next); //随机立减
            map.get(node).random=map.get(node.random);
            node=node.next;
        }
        return map.get(head);
    }
}


解法二:原地复制


class Solution {
    public Node copyRandomList(Node head) {
        if(head==null){
            return null;
        }
        //原地复制节点
        Node current=head;
        while(current!=null){
            Node clone=new Node(current.val);
            Node temp= current.next;
            clone.next=current.next;
            current.next=clone;
            current=temp;
        }
        //处理随机节点,要注意画图和校验
        current=head;
        while(current!=null){
            if(current.random!=null){
                 current.next.random=current.random.next;
            }
            current=current.next.next;
        }
        ///将两个链表拆开
        Node newHead=new Node(-1);
        newHead=head.next;
        current=head;
        while(current.next!=null){
         Node temp=current.next;
         current.next=current.next.next;
         current=temp;
        }
        return newHead;
    }
}
目录
相关文章
|
4月前
链表指针的传参,传值和传地址
本文讨论了链表操作中指针传参的问题,特别是指针的传值与传地址的区别,并提供了修正代码,以确保链表插入操作能正确地修改指针指向的地址。
28 1
链表指针的传参,传值和传地址
|
9月前
|
存储 C语言
用指针处理链表
用指针处理链表
81 3
|
4月前
|
存储
一篇文章了解区分指针数组,数组指针,函数指针,链表。
一篇文章了解区分指针数组,数组指针,函数指针,链表。
33 0
|
4月前
|
C语言
无头链表二级指针方式实现(C语言描述)
本文介绍了如何在C语言中使用二级指针实现无头链表,并提供了创建节点、插入、删除、查找、销毁链表等操作的函数实现,以及一个示例程序来演示这些操作。
56 0
|
7月前
【数据结构OJ题】复制带随机指针的链表
力扣题目——复制带随机指针的链表
65 1
【数据结构OJ题】复制带随机指针的链表
|
6月前
|
Python
【Leetcode刷题Python】138. 复制带随机指针的链表
LeetCode上题目“138. 复制带随机指针的链表”的Python解决方案,包括两种方法:一种是在每个节点后复制一个新节点然后再分离出来形成新链表;另一种是构建一个字典来跟踪原始节点与其副本之间的映射关系,从而处理新链表的构建。
33 1
|
6月前
|
存储 算法 数据处理
指针与链表
指针与链表
105 0
|
8月前
|
算法
【经典LeetCode算法题目专栏分类】【第7期】快慢指针与链表
【经典LeetCode算法题目专栏分类】【第7期】快慢指针与链表
|
9月前
|
存储 C语言
链表—初始化指针变和创建新的节点------区别应用分析
链表—初始化指针变和创建新的节点------区别应用分析
|
9月前
|
存储 缓存 搜索推荐
指针链表
指针链表
61 0