https://leetcode.com/problems/copy-list-with-random-pointer/
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.
用hashtable实现很简单,就是记录一下已经出现过的node就行了。但是需要O(n) space,所以另一种方法见这里:http://blog.youkuaiyun.com/fightforyourdream/article/details/16879561 ,是把新node插入到原来的链表,所有的指针都复制之后,再把两个链表分开。
目前我只实现了hashtable的方法,有空再做做那种方法吧:
public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {
if(head==null) return null;
HashMap<RandomListNode, RandomListNode> map= new HashMap<RandomListNode, RandomListNode>();
RandomListNode node = head;
RandomListNode dummy = new RandomListNode(0);
RandomListNode pre = dummy;
RandomListNode newnode;
while(node!=null){
if(map.containsKey(node)){
newnode = map.get(node);
}
else{
newnode = new RandomListNode(node.label);
map.put(node, newnode);
}
pre.next = newnode;
if (node.random != null) {
if (map.containsKey(node.random)) {
newnode.random = map.get(node.random);
} else {
newnode.random = new RandomListNode(node.random.label);
map.put(node.random, newnode.random);
}
}
// if (node.next != null) {
// if (map.containsKey(node.next)) {
// newnode.next = map.get(node.next);
// } else {
// newnode.next = new RandomListNode(node.next.label);
// map.put(node.next, newnode.next);
// }
// }
pre = newnode;
node = node.next;
}
return dummy.next;
}
}
上面注释的代码是冗余的,有没有都能过,因为next本来就是下一次要访问的。写代码的时候一定要注意这种问题。