題目描述
輸入一個(gè)復(fù)雜鏈表(每個(gè)節(jié)點(diǎn)中有節(jié)點(diǎn)值劫窒,以及兩個(gè)指針,一個(gè)指向下一個(gè)節(jié)點(diǎn)诈泼,另一個(gè)特殊指針指向任意一個(gè)節(jié)點(diǎn))煤禽,返回結(jié)果為復(fù)制后復(fù)雜鏈表的head。(注意檬果,輸出結(jié)果中請(qǐng)不要返回參數(shù)中的節(jié)點(diǎn)引用唐断,否則判題程序會(huì)直接返回空)
import java.util.HashMap;
import java.util.Map;
public class Solution {
public RandomListNode Clone(RandomListNode pHead) {
Map<Integer,RandomListNode> map = new HashMap<Integer,RandomListNode>();
if(pHead == null) {
return null;
}
RandomListNode node = pHead;
RandomListNode root = null;
RandomListNode pre = null;
while(node != null) {
if(map.containsKey(node.label)) {
pre.next = map.get(node.label);
pre = pre.next;
if(node.random != null) {
if(map.containsKey(node.random.label)) {
pre.random = map.get(node.random.label);
}else {
RandomListNode random = new RandomListNode(node.random.label);
map.put(random.label, random);
pre.random = random;
}
}
node = node.next;
}else {
RandomListNode temp = new RandomListNode(node.label);
if(root == null) {
pre = root = temp;
}else {
pre.next = temp;
pre = pre.next;
}
if(node.random != null) {
if(map.containsKey(node.random.label)) {
pre.random = map.get(node.random.label);
}else {
RandomListNode random = new RandomListNode(node.random.label);
map.put(random.label, random);
pre.random = random;
}
}
node = node.next;
}
}
return root;
}
}