剑指 Offer 35. 复杂链表的复制(java&python3)

这篇博客探讨了如何高效地复制一个带有随机指针的链表。作者提供了两种Java实现方法,一种是递归配合哈希映射,另一种是迭代方式。通过哈希映射,可以快速查找和复制已处理过的节点,确保复制的链表正确连接。这种方法对于解决复杂链表问题非常有效。
摘要由CSDN通过智能技术生成

题解中有位大佬说:random指针可能指向任何一个已经复制过的节点,所有使用map保存已经生成过的节点,以方便后续获取

看了另一位大佬用了递归+hashmap 对各位大佬只能说:谢谢谢谢

class Solution {
    Map<Node,Node> map=new HashMap<>();

    public Node copyRandomList(Node head) {
        if(head==null){
            return null;
        }

        Node cur=head;
        if(map.containsKey(head)){
            cur=map.get(head);
            return cur;
        }else{
            cur=new Node(head.val);
            map.put(head,cur);
            cur.next=copyRandomList(head.next);
            cur.random=copyRandomList(head.random);
            return cur;
        }
    }
}
class Solution {
    public Node copyRandomList(Node head) {
        if(head == null){
            return null;
        }
        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);
    }
}

 

python3:

dic["键"]="值"

get('键','可以自己指定内容')

class Solution:
    def copyRandomList(self, head: 'Node') -> 'Node':
        if not head:
            return 
        dic = {}
        cur = head
        while cur:
            dic[cur] = Node(cur.val)
            cur = cur.next
        cur = head
        while cur:
            dic[cur].next = dic.get(cur.next)
            dic[cur].random = dic.get(cur.random)
            cur = cur.next
        return dic[head]

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值