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

相关推荐

不愿透露姓名的神秘牛友
07-02 18:35
简历上把1个月实习写成了3个月,会进行背调吗?
码农索隆:一个月有一个月的实习经历,三个月有三个月的实习经历
点赞 评论 收藏
分享
zYvv:双一流加大加粗再标红,然后广投。主要是获奖荣誉不够,建议开始不用追求大厂,去别的厂子刷下实习。
点赞 评论 收藏
分享
牛客84809583...:举报了
点赞 评论 收藏
分享
评论
9
1
分享

创作者周榜

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