题目链接:复杂链表的复制
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 head) {if (head == null) return head;RandomListNode res = new RandomListNode(-1);// 哈希表,key为原始链表的节点,value为原始链表节点的拷贝节点HashMap<RandomListNode, RandomListNode> mp = new HashMap<>();RandomListNode cur = head;RandomListNode pre = res;while(cur != null){// 拷贝节点RandomListNode copy = new RandomListNode(cur.label);mp.put(cur, copy);pre.next = copy;cur = cur.next;pre = pre.next;}// 遍历哈希表,建立random关系for(HashMap.Entry<RandomListNode, RandomListNode> entry: mp.entrySet()){if(entry.getKey().random == null) entry.getValue().random = null;else entry.getValue().random = mp.get(entry.getKey().random);}return res.next;}
}