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.
这道题其实还蛮绕的
假设链表为1->3->2->5首先进行普通的拷贝
接着:假设1的随之指针指向2.
那么新生成的链表1->3->2->5怎么知道让1指向2呢?
需要几步:
1. 1 知道指向2
2. 即知道值为2 指向index = 2的节点(从0开始) hashmap: index to node
3. 如何知道index = 2的节点呢?假设原来的1指向2 这个节点,要是2这个节点又知道自己的下标 就可了。hashmap: node to index
运行时间:
代码:
public class CopyListwithRandomPointer {
public RandomListNode copyRandomList(RandomListNode head) {
Map<RandomListNode, Integer> nodeToIndexMap = new HashMap<>();
Map<Integer, RandomListNode> indexToNodeMap = new HashMap<>();
RandomListNode fakeHead = new RandomListNode(-1), fakeNode = fakeHead;
RandomListNode cur = head;
int i = 0;
while (cur != null) {
nodeToIndexMap.put(cur, i);
fakeNode.next = new RandomListNode(cur.label);
fakeNode = fakeNode.next;
cur = cur.next;
i++;
}
i = 0;
RandomListNode newcur = fakeHead.next;
while (newcur != null) {
indexToNodeMap.put(i, newcur);
newcur = newcur.next;
i++;
}
newcur = fakeHead.next;
cur = head;
while (newcur != null) {
newcur.random = indexToNodeMap.get(nodeToIndexMap.get(cur.random));
newcur = newcur.next;
cur = cur.next;
}
return fakeHead.next;
}
}