題目描述
輸入一個複雜鏈表(每個節點中有節點值,以及兩個指針,一個指向下一個節點,另一個特殊指針指向任意一個節點),返回結果爲複製後複雜鏈表的head。(注意,輸出結果中請不要返回參數中的節點引用,否則判題程序會直接返回空)
思路很簡單使用map進行記錄,鍵對應原有鏈表節點,值對應copy鏈表中要用到的新對象。如果map中已經存儲相應的值,進行復用,否則進行存儲。
/*
public class RandomListNode {
int label;
RandomListNode next = null;
RandomListNode random = null;
RandomListNode(int label) {
this.label = label;
}
}
*/
import java.util.*;
public class Solution {
public RandomListNode Clone(RandomListNode pHead)
{
if(pHead==null)return null;
RandomListNode newHead = null;
RandomListNode oldList = pHead;
RandomListNode newList = null;
HashMap<RandomListNode,RandomListNode> map = new HashMap<RandomListNode,RandomListNode>();
while(oldList!=null){
if(newHead==null){
newHead = new RandomListNode(pHead.label);
newList = newHead;
map.put(pHead,newHead);
}else{
if(oldList.next!=null&&map.containsKey(oldList.next)){
newList.next = map.get(oldList.next);
}else{
if(oldList.next!=null){
RandomListNode tem = new RandomListNode(oldList.next.label);
newList.next = tem;
map.put(oldList.next,tem);
}
}
if(oldList.random!=null&&map.containsKey(oldList.random)){
newList.random = map.get(oldList.random);
}else{
if(oldList.random!=null){
RandomListNode randomTem = new RandomListNode(oldList.random.label);
newList.random = randomTem;
map.put(oldList.random,randomTem);
}
}
oldList = oldList.next;
newList = newList.next;
}
}
return newHead;
}
}