leetcode easy和medium的题总算刷完了。认真刷Hard了,Hard题重思路。
这题的思路就是复制原来的list, 每个node都double, 然后copy random pointer就是相当于node.next.random=node.random.next, random依次指向下一个。最后分开两个list, return copy list.
public RandomListNode copyRandomList(RandomListNode head) {
if(head==null){
return null;
}
RandomListNode node = head;
while(node!=null){
RandomListNode newNode = new RandomListNode(node.label);
newNode.next = node.next;
node.next = newNode;
node = newNode.next;
}
node = head;
while(node!=null){
if(node.random!=null){
node.next.random = node.random.next;
}
node = node.next.next;
}
RandomListNode newHead = head.next;
node = head;
while(node!=null){
RandomListNode newNode = node.next;
node.next = newNode.next;
if(newNode.next!=null){
newNode.next = newNode.next.next;
}
node = node.next;
}
return newHead;
}