https://leetcode.com/problems/copy-list-with-random-pointer/description/
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
package go.jacob.day804;
import java.util.HashMap;
import java.util.Map;
/**
* 138. Copy List with Random Pointer 题意是:返回一个链表的深拷贝
*
* @author Jacob
*
*/
public class Demo2 {
/*
* 推荐解答:使用map,每一个原链表节点,在map中对应新链表的节点
*/
public RandomListNode copyRandomList(RandomListNode head) {
if (head == null)
return null;
Map<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
RandomListNode node = head;
while (node != null) {
map.put(node, new RandomListNode(node.label));
node = node.next;
}
node = head;
while (node != null) {
map.get(node).next = map.get(node.next);
map.get(node).random = map.get(node.random);
node = node.next;
}
return map.get(head);
}
/*
* 剑指offer中的解答,会改变原链表的结构。 需要额外操作来恢复原链表的结构
* 链表的题目画图比较清晰
*/
public RandomListNode copyRandomList_1(RandomListNode head) {
if (head == null)
return null;
RandomListNode node = head;
// 在原链表每个节点后插入一个复制的节点
while (node != null) {
RandomListNode newNode = new RandomListNode(node.label);
RandomListNode temp = node.next;
node.next = newNode;
newNode.next = temp;
node = temp;
}
node = head;
// 复制随机节点
while (node != null) {
RandomListNode tempRandom = node.random;
if (tempRandom != null) {
node.next.random = tempRandom.next;
} else
node.next.random = null;
node = node.next.next;
}
//恢复原链表和生成新链表
RandomListNode newHead = head.next;
RandomListNode newNode = head.next;
node = head;
while (newNode != null) {
node.next=newNode.next;
node = newNode.next;
if (node != null){
newNode.next = node.next;
}
else
newNode.next = null;
newNode = newNode.next;
}
return newHead;
}
private class RandomListNode {
int label;
RandomListNode next, random;
RandomListNode(int x) {
this.label = x;
}
};
}