【小熊刷题】Copy List with Random Pointer <可再复习思路>

Copy List with Random Pointer

Question

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

Return a deep copy of the list.

*Difficulty: Hard, Frequency: High

https://leetcode.com/problems/copy-list-with-random-pointer/

My Solution

看了一下提示搞出来的,其实大概的意思就是,用一个map来记住原来的liskedlist的每个node对应着新建linkedlist(deepcopy)的哪个node。<之后书上的另一个方法其实也是这个意思,只不过通过改linkedlist结构节省map的空间而已,本质上没太大区别>

/**
 * 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) {
        Map<RandomListNode, RandomListNode> map = new HashMap<>();
        RandomListNode p = head;
        RandomListNode dummyHead = new RandomListNode(0);
        RandomListNode q = dummyHead;
        while(p != null){
            q.next = new RandomListNode(p.label);
            map.put(p, q.next);
            p = p.next;
            q = q.next;
        }
        p = head;
        q = dummyHead;
        while(p != null){
            q.next.random = map.get(p.random);
            p = p.next;
            q = q.next;
        }
        return dummyHead.next;
    }
}

To be continued, 回去再看一下直接把copy的node加在原node后面变成一个双倍长度的linkedlist再去掉之前的node的方法…

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值