topic:
A complex input list (each node has a node value, and two pointers, one pointing to the next node, a special pointer to any other node), returns a value after the head of the list replication complex. (Note that the output results do not return parameter node reference, otherwise the program will return empty sentenced questions directly)
answer:
Solution one:
Read other people's ideas to write, ideas are as follows :( sources see the watermark)
code show as below:
/*
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;
}
//next
RandomListNode current = pHead;
while(current!=null){
RandomListNode node = new RandomListNode(current.label);
node.next = current.next;
current.next = node;
current = node.next;
}
//random
current = pHead;
while(current!=null){
current.next.random = (current.random==null?null:current.random.next);
current = current.next.next;
}
//result
current = pHead;
RandomListNode result = pHead.next;
while(current!=null){
RandomListNode cloneNode = current.next;
current.next = cloneNode.next;
cloneNode.next = cloneNode.next==null?null:cloneNode.next.next;
current = current.next;
}
return result;
}
}