别的都不说,这部分题对我来说,首先就是看不懂题意
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.
/*** Definition for singly-linked list with a random pointer.
* class RandomListNode {
* int label;
* RandomListNode next, random;
* RandomListNode(int x) { this.label = x; }
* };
*/
1 label和random,next关系,做hashmap的时候怎么放key 和value?
2 初一看题查了deep copy的说明,但是还是给想复杂了,人家就是让你copy而已,把random信息也给copy过去,而不是reorder这个list。 这样就好理解ref link里面题解里“如果要copy一个带有random pointer的list,主要的问题就是有可能这个random指向的位置还没有被copy到,所以解决方法都是多次扫描list。”的意义
ref http://www.cnblogs.com/springfor/p/3864457.html
3 HashMap 里面存的是指向node的指针还是node本身呢?
4 第二种作法,不利用hashmap,关键是看懂node.next.random = node.random.next
那些破人,连个“滚”的眼神都懒得甩
soln 1
public RandomListNode copyRandomList(RandomListNode head) {
//http://www.cnblogs.com/springfor/p/3864457.html
if(head==null) return null;
//soln 1 HashMap 遍历2次list,所以时间复杂度是O(2n)=O(n),然后使用了HashMap,所以空间复杂度是O(n)。
RandomListNode newhd = new RandomListNode(head.label);
RandomListNode oldhd = head;
RandomListNode oldp = head.next;
RandomListNode newp = newhd;
HashMap<RandomListNode, RandomListNode> hm = new HashMap<RandomListNode, RandomListNode>();
hm.put(oldhd, newhd); //Map<K,V> , which is key,which is value?
while(oldp!=null){
RandomListNode newnode = new RandomListNode(oldp.label);
newp.next = newnode;
newp = newp.next;
hm.put(oldp,newp);
oldp = oldp.next;
}
oldp = head;
newp = newhd;
while(oldp!=null){
newp.random = hm.get(oldp.random);
newp = newp.next;
oldp = oldp.next;
}
return newhd;
soln 2
//soln 2 a) replica old nodes twice, b) replica node.next(which is node's replica).random = node.random.next(which is random's replica) , c) separate node and its replica
RandomListNode node = head;
while(node!=null){
RandomListNode newnode = new RandomListNode(node.label);
newnode.next = node.next;
node.next = newnode; // a) replica old nodes twice
node =newnode.next;
}
node = head;
while(node!=null){
if(node.random!=null)
node.next.random = node.random.next; // b) replica node.next(which is node's replica).random = node.random.next(which is random's replica)
node = node.next.next;
}
node = head;
RandomListNode newhd = head.next;
while(node!=null){
RandomListNode rep = node.next;
node.next = rep.next;
if(rep.next!=null)
rep.next = rep.next.next;
node = node.next;
}
return newhd;
}
}