含随机指针链表的深拷贝(两种方法)

题目描述:
请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。

方法一:
1.将每一个节点复制后插入到原节点的后面,新的random域先初始化为null
2.新节点的random为旧节点random指向的下一个节点
3.拆分:将这个链表的新旧节点拆分开,返回新节点

class A{
    int data;
    A next;
    A random;
    public A(int data,A next,A random){
        this.data=data;
        this.next=next;
        this.random=random;
    }
}
public class RandomCopy {
    A head;
    public A copyRandomList(){
        if(this.head==null){
            return null;
        }
        A cur=this.head;
        while(cur!=null){
            A node=new A(cur.data,cur.next,null);
            A tmp=cur.next;
            cur.next=node;
            cur=tmp;
        }
        cur=this.head;
        while(cur!=null){
            if(cur.random!=null){
                cur.next.random=cur.random.next;
            }else{
                cur.next.random=null;
            }
            cur=cur.next.next;
        }
        //拆
        cur=this.head;
        A newHead=cur.next;
        while(cur.next!=null){
            A tmp=cur.next;
            cur.next=tmp.next;
            cur=tmp;
        }
        return newHead;
    }
}

方法二:借助HashMap存储
1.遍历整个链表,将原节点作为键,将复制的新节点作为值存入map中
2.在遍历一遍链表,将新节点的next域和random域根据原节点赋值

class Solution {
    public Node copyRandomList(Node head) {
       Map<Node,Node> map=new HashMap<>();
       Node cur=head;
       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);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值