Copy List with Random Pointer 带随机指针的链表的拷贝

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

这道题其实还蛮绕的

假设链表为1->3->2->5首先进行普通的拷贝

接着:假设1的随之指针指向2.

那么新生成的链表1->3->2->5怎么知道让1指向2呢?

需要几步:

1. 1 知道指向2

2. 即知道值为2 指向index = 2的节点(从0开始) hashmap: index to node

3. 如何知道index = 2的节点呢?假设原来的1指向2 这个节点,要是2这个节点又知道自己的下标 就可了。hashmap: node to index

运行时间:


代码:

public class CopyListwithRandomPointer {
    public RandomListNode copyRandomList(RandomListNode head) {
        Map<RandomListNode, Integer> nodeToIndexMap = new HashMap<>();
        Map<Integer, RandomListNode> indexToNodeMap = new HashMap<>();
        RandomListNode fakeHead = new RandomListNode(-1), fakeNode = fakeHead;
        RandomListNode cur = head;
        int i = 0;
        while (cur != null) {
            nodeToIndexMap.put(cur, i);
            fakeNode.next = new RandomListNode(cur.label);
            fakeNode = fakeNode.next;
            cur = cur.next;
            i++;
        }
        i = 0;
        RandomListNode newcur = fakeHead.next;
        while (newcur != null) {
            indexToNodeMap.put(i, newcur);
            newcur = newcur.next;
            i++;
        }
        newcur = fakeHead.next;
        cur = head;
        while (newcur != null) {
            newcur.random = indexToNodeMap.get(nodeToIndexMap.get(cur.random));
            newcur = newcur.next;
            cur = cur.next;
        }
        return fakeHead.next;
    }
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值