输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
思路:三个循环分别做了:
1.复制链表中的每一个节点并插入每个节点的后面;
2.赋予复制节点random;
3.分离两个链表
public RandomListNode Clone(RandomListNode pHead){
if(pHead == null)
return null;
RandomListNode cur = pHead;
while(cur != null){
RandomListNode cur_clone = new RandomListNode(cur.label);
RandomListNode tmp = cur.next;
cur.next = cur_clone;
cur_clone.next = tmp;
cur = tmp;
}
cur = pHead;
while(cur != null){
if(cur.random !=null){
RandomListNode cur_random = cur.random;
cur.next.random = cur_random.next;
}
cur = cur.next.next;
}
cur = pHead;
RandomListNode result = pHead.next;
while(cur != null){
RandomListNode cur_clone = cur.next;
cur.next = cur_clone.next;
cur_clone.next = cur_clone.next == null ? null : cur_clone.next.next;
cur = cur.next;
}
return result;
}
HashMap版:
public RandomListNode Clone(RandomListNode pHead){
if(pHead == null)return null;
RandomListNode clone_pHead = new RandomListNode(pHead.label);
HashMap<RandomListNode,RandomListNode> map = new HashMap<>();
RandomListNode cur_node = pHead,cur_clone_node = clone_pHead;
//next
while(cur_node != null) {
map.put(cur_node,cur_clone_node);
if(cur_node.next != null)
cur_clone_node.next = new RandomListNode(cur_node.next.label);
cur_clone_node = cur_clone_node.next;
cur_node = cur_node.next;
}
//random
cur_node = pHead;
cur_clone_node = clone_pHead;
while(cur_node != null) {
if(cur_node.random != null)
map.get(cur_node).random = map.get(cur_node.random);
cur_node = cur_node.next;
}
return clone_pHead;
}