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-04 14:35
点赞 评论 收藏
分享
那一天的Java_J...:他本来公司就是做这个的,不就是正常的游戏客户端和服务器开发,软硬件联动,有啥恶心不恶心的,提前告诉你就是怕你接受不了,接受不了就没必要再往后走流程浪费时间,虽然这公司是一坨。
点赞 评论 收藏
分享
评论
9
1
分享

创作者周榜

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