剑指offer 复杂链表的复制

该博客讨论了两种方法来克隆一个带有随机指针的链表。第一种方法是通过创建两个ArrayList分别存储源链表和目标链表的节点,然后遍历并建立随机指针的连接。第二种优化方法利用HashMap建立源节点和目标节点的一一对应关系,从而更高效地复制随机指针。这两种方法都是为了在保持链表结构的同时复制其随机指针属性。
摘要由CSDN通过智能技术生成

题目

在这里插入图片描述

解法一

我们先把所有的节点复制下来,然后将源节点存在一个arraylist里面,目的链表存在一个arraylist里面,然后遍历一遍原节点的arraylist找到它的每个节点的random对应的index,在用这个index来找到dst里面的节点的值。

/*
public class RandomListNode {
    int label;
    RandomListNode next = null;
    RandomListNode random = null;

    RandomListNode(int label) {
        this.label = label;
    }
}
*/
import java.util.*;
public class Solution {
    public RandomListNode Clone(RandomListNode pHead) {
        if(pHead==null)return null;
        ArrayList<RandomListNode> src=new ArrayList<>();
        ArrayList<RandomListNode> dst=new ArrayList<>();
        while(pHead!=null){
            RandomListNode temp=new RandomListNode(pHead.label);
            src.add(pHead);
            dst.add(temp);
            pHead=pHead.next;
            
        }
        int num=src.size();
        //这里需要加一个null是因为之后的next赋值的时候需要的
        dst.add(null);
        for (int i=0;i<num;i++){
            int index;
            dst.get(i).next=dst.get(i+1);
            if(src.get(i).random!=null){
                index=src.indexOf(src.get(i).random);
                dst.get(i).random=dst.get(index);
            }
               
            else{
                dst.get(i).random=null;
            }
                
            
            
        }
        return dst.get(0);
        
    }
}

解法一的优化

解法一实际上就是建立了一个对应关系,src和dst每一个index对应的节点就是复制链表前后的两个节点,所以我们可以直接使用map来建立这个对应的关系


/*
public class RandomListNode {
    int label;
    RandomListNode next = null;
    RandomListNode random = null;

    RandomListNode(int label) {
        this.label = label;
    }
}
*/
import java.util.*;
public class Solution {
    public RandomListNode Clone(RandomListNode pHead) {
        HashMap<RandomListNode,RandomListNode> h=new HashMap<>();
        RandomListNode prev=new RandomListNode(0);
        RandomListNode src=pHead;
        while(pHead!=null){
            RandomListNode temp=new RandomListNode(pHead.label);
            prev.next=temp;
            h.put(pHead,temp);
            pHead=pHead.next;
            prev=temp;
        }
        prev.next=null;
        RandomListNode dst=h.get(src);
        RandomListNode ans=dst;
        while(src!=null){
            dst.random=h.get(src.random);
            dst=dst.next;
            src=src.next;
            
        }
        
        return ans;
        
        
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值