HashMap 一步到位

复杂链表的复制

http://www.nowcoder.com/questionTerminal/f836b2c43afc4b35ad6adc41ec941dba

//保存原链表节点和复制链表节点的对应
    HashMap<RandomListNode, RandomListNode> hashMap = new HashMap<>();
public RandomListNode Clone(RandomListNode pHead) {
    if (pHead == null)
        return null;
    RandomListNode randomListNode = new RandomListNode(pHead.label);
    hashMap.put(pHead, randomListNode);

    //移动的指针
    RandomListNode temp = randomListNode ;
    RandomListNode cur = pHead;

    while (cur != null) {
    //为next 节点赋值
        if (cur.next != null) {
            if (!hashMap.containsKey(cur.next))
                hashMap.put(cur.next, new RandomListNode(cur.next.label));
            temp.next = hashMap.get(cur.next);
        }
       //为random 节点赋值
        if (cur.random != null) {
            if (!hashMap.containsKey(cur.random))
                hashMap.put(cur.random, new RandomListNode(cur.random.label));
            temp.random = hashMap.get(cur.random);
        }
        //移动指针
        cur = cur.next;
        temp = temp.next;
    }
    return randomListNode;
    }
全部评论
为什么不是return temp
点赞 回复 分享
发布于 2020-08-14 16:50
就是搞不懂为什么非要用个map集合来存节点,直接赋new出来的值不行吗
点赞 回复 分享
发布于 2020-04-04 10:48

相关推荐

牛客97567122...:我最近投的几个,都是要不已读不回,要不不回,还有直接拒绝的
点赞 评论 收藏
分享
评论
9
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务