描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针random指向一个随机节点),请对此链表进行深拷贝,并返回拷贝后的头结点。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)。 下图是一个含有5个结点的复杂链表。图中实线箭头表示next指针,虚线箭头表示random指针。为简单起见,指向null的指针没有画出。
示例:
输入:{1,2,3,4,5,3,5,#,2,#}
输出:{1,2,3,4,5,3,5,#,2,#}
解析:我们将链表分为两段,前半部分{1,2,3,4,5}为ListNode,后半部分{3,5,#,2,#}是随机指针域表示。
以上示例前半部分可以表示链表为的ListNode:1->2->3->4->5
后半部分,3,5,#,2,#分别的表示为
1的位置指向3,2的位置指向5,3的位置指向null,4的位置指向2,5的位置指向null
如下图:
列表
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 (pHead == null) {
return null;
}
List<RandomListNode> list = new ArrayList<>();
List<RandomListNode> newList = new ArrayList<>();
//前置指针
RandomListNode head = new RandomListNode(0);
//clone+next
while (pHead != null) {
RandomListNode newHead = new RandomListNode(pHead.label);
head.next = newHead;
newList.add(newHead);
list.add(pHead);
pHead = pHead.next;
head = head.next;
}
//random
for (int i = 0; i < list.size(); i++) {
RandomListNode randomHead = list.get(i).random;
if (randomHead != null) {
int random = list.indexOf(randomHead);
newList.get(i).random = newList.get(random);
}
}
return newList.get(0);
}
}
Map
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 (pHead == null) {
return pHead;
}
//克隆映射关系
HashMap<RandomListNode, RandomListNode> hashMap = new HashMap<>();
//前置指针
RandomListNode newHead = new RandomListNode(0);
RandomListNode oldHead = pHead;
RandomListNode result = newHead;
while (oldHead != null) {
RandomListNode tmp = new RandomListNode(oldHead.label);
newHead.next = tmp;
hashMap.put(oldHead, tmp);
oldHead = oldHead.next;
newHead = newHead.next;
}
hashMap.forEach((key, value)-> {
// if(key.random!=null){
// value.random = hashMap.get(key.random);
// }
value.random = key.random == null ? null : hashMap.get(key.random);
});
return result.next;
}
}