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.
一开始没懂啥是random pointer。。其实就是除了next还有一个random的指向不明。
deep copy就是完全copy一份出来。
这个题有两种思路,第一种就是按照基本复制方法复制一遍,random的就先存在map里,在遍历第二遍的时候复制random的部分。
第二种,就是把复制的new node 连接在原来的node后面,再把两个list分离。
写的是第二种。
/**
* Definition for singly-linked list with a random pointer.
* class RandomListNode {
* int label;
* RandomListNode next, random;
* RandomListNode(int x) { this.label = x; }
* };
*/
public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {
if(head == null){
return null;
}
RandomListNode present = head;
while(present != null){
RandomListNode node = new RandomListNode(present.label);
node.next = present.next;
present.next = node;
present = node.next;
}
present = head;
while(present != null){
if(present.random != null){
present.next.random = present.random.next;
}else{
present.next.random = null;
}
present = present.next.next;
}
RandomListNode newHead = head.next;
present = head;
RandomListNode newnode = head.next;
while(present!= null && newnode != null){
present.next = present.next.next;
if(newnode.next == null){
return newHead;
}
present = present.next;
newnode.next = newnode.next.next;
newnode = newnode.next;
}
return newHead;
}
}