题解 | #复杂链表的复制#

复杂链表的复制

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

import java.util.*;
/*
public class RandomListNode {
    int label;
    RandomListNode next = null;
    RandomListNode random = null;

    RandomListNode(int label) {
        this.label = label;
    }
}
*/
public class Solution {
    public RandomListNode Clone(RandomListNode pHead) {
        
        if (null == pHead) {
            return null;
        }
        
        RandomListNode tmp = pHead;
        Queue<RandomListNode> queue = new LinkedList<>();
        HashMap<Integer, RandomListNode> hashMap = new HashMap<>(); // 值
        while (null != tmp) {
            RandomListNode node = new RandomListNode(tmp.label);
            queue.add(node);
            hashMap.put(node.label, node);
            tmp = tmp.next;
        }
        RandomListNode head = queue.poll();
        tmp = head;
        while (!queue.isEmpty()) {
            tmp.next = queue.poll();
            tmp = tmp.next;
        }
        tmp.next = null;
        tmp = pHead;
        while (null != tmp) {
            RandomListNode currentNode = hashMap.get(tmp.label);
            RandomListNode tmpRandom = tmp.random;
            if (null != tmpRandom) {
                RandomListNode currentRandom = hashMap.get(tmpRandom.label);
                currentNode.random = currentRandom;
            }
            tmp = tmp.next;
        }
        return head;
    }
}
全部评论

相关推荐

04-08 16:35
门头沟学院 Java
站队站对牛:实在是恶心的公司
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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