Copy List with Random Pointer leetcode java 走地牙

这篇博客介绍了解决LeetCode中Copy List with Random Pointer问题的Java实现。通过创建新的链表并维护一个映射表,将原始链表和复制链表节点一一对应,然后遍历设置新链表的random指针。
摘要由CSDN通过智能技术生成

/**
 * Definition for singly-linked list with a random pointer.
 * class RandomListNode {
 *     int label;
 *     RandomListNode next, random;
 *     RandomListNode(int x) { this.label = x; }
 * };
 */
public class Solution {
    public RandomListNode copyRandomList(RandomListNode head) {
        if(head == null) return null;
        //建立一个用于遍历head的指针;
        RandomListNode tempHead = head;
        //建立新的list;
        RandomListNode newHead = new RandomListNode(head.label);
        //建立用于遍历新list的指针;
        RandomListNode tempNewHead = newHead;
        //建立老list与新list的对应关系;
        HashMap<RandomListNode, RandomListNode> mapping = new HashMap<>();
        mapping.put(tempHead, tempNewHead);
        //先将所有老与新的关系放入map 再把next关系写好;
        while(tempHead.next != null) {
            tempNewHead.next = new RandomListNode(tempHead.next.label);
            tempNewHead = tempNewHead.next;
            tempHead = tempHead.next;
            mapping.put(tempHead, tempNewHead);
        }
        //重新归于头部;
        tempHead = head;
        tempNewHead = newHead;
        //再遍历设置一遍random
        while(tempHead != null) {
            tempNewHead.random = mapping.get(tempHead.random);
            tempNewHead = tempNewHead.next;
            tempHead = tempHead.next;
        }
        return newHead;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值