/*
public class RandomListNode {
int label;
RandomListNode next = null;
RandomListNode random = null;
RandomListNode(int label) {
this.label = label;
}
}
*/
public class Solution {
public RandomListNode Clone(RandomListNode pHead)
{
if(pHead==null) return null;
CloneNodes(pHead);
ConnectSiblingNodes(pHead);
return ReconnectNodes(pHead);
}
public RandomListNode CloneNodes(RandomListNode pHead){
RandomListNode pNode=pHead;
while(pNode!=null){
RandomListNode pCloned = new RandomListNode(pNode.label);
pCloned.next=pNode.next;
pCloned.random=null;
pNode.next=pCloned;
pNode=pCloned.next;
}
return pHead;
}
public RandomListNode ConnectSiblingNodes(RandomListNode pHead){
RandomListNode pNode=pHead;
while(pNode!=null){
if(pNode.random!=null){
pNode.next.random=pNode.random.next;
}
pNode=pNode.next.next;
}
return pHead;
}
public RandomListNode ReconnectNodes(RandomListNode pHead){
RandomListNode pNode=pHead;
RandomListNode pClonedNode=null;
RandomListNode pClonedHead=null;
if(pNode!=null){
pClonedNode=pClonedHead=pNode.next;
pNode.next=pClonedNode.next;
pNode=pNode.next;
}
while(pNode!=null){
pClonedNode.next=pNode.next;
pClonedNode=pClonedNode.next;
pNode.next=pClonedNode.next;
pNode=pNode.next;
}
return pClonedHead;
}
}
public class RandomListNode {
int label;
RandomListNode next = null;
RandomListNode random = null;
RandomListNode(int label) {
this.label = label;
}
}
*/
public class Solution {
public RandomListNode Clone(RandomListNode pHead)
{
if(pHead==null) return null;
CloneNodes(pHead);
ConnectSiblingNodes(pHead);
return ReconnectNodes(pHead);
}
public RandomListNode CloneNodes(RandomListNode pHead){
RandomListNode pNode=pHead;
while(pNode!=null){
RandomListNode pCloned = new RandomListNode(pNode.label);
pCloned.next=pNode.next;
pCloned.random=null;
pNode.next=pCloned;
pNode=pCloned.next;
}
return pHead;
}
public RandomListNode ConnectSiblingNodes(RandomListNode pHead){
RandomListNode pNode=pHead;
while(pNode!=null){
if(pNode.random!=null){
pNode.next.random=pNode.random.next;
}
pNode=pNode.next.next;
}
return pHead;
}
public RandomListNode ReconnectNodes(RandomListNode pHead){
RandomListNode pNode=pHead;
RandomListNode pClonedNode=null;
RandomListNode pClonedHead=null;
if(pNode!=null){
pClonedNode=pClonedHead=pNode.next;
pNode.next=pClonedNode.next;
pNode=pNode.next;
}
while(pNode!=null){
pClonedNode.next=pNode.next;
pClonedNode=pClonedNode.next;
pNode.next=pClonedNode.next;
pNode=pNode.next;
}
return pClonedHead;
}
}