Enter a complex list with node values in each node, and two pointers, one pointing to the next node, and the other a special pointer to any node.
A clever solution is this: copy next as it turns out to be a->b->c into A->a '->b->b '->c->c ', and then navigate through the previous random pointer after a random pointer, Then split into two linked lists. Both time complexity and spatial complexity are O (n).
Implementation code:
/*Public class Randomlistnode {int label; Randomlistnode next = null; Randomlistnode random = null; Randomlistnode (int label) {this.label = label; }}*/ Public classSolution { Publicrandomlistnode Clone (Randomlistnode phead) {if(phead==NULL) return NULL; Randomlistnode Curnode=Phead; while(Curnode! =NULL) {randomlistnode node=NewRandomlistnode (Curnode.label); Node.next=Curnode.next; Curnode.next=node; Curnode=Node.next; } Curnode=Phead; while(Curnode! =NULL) { if(Curnode.random! =NULL) {CurNode.next.random=CurNode.random.next; } Curnode=CurNode.next.next; } Curnode=Phead; Randomlistnode Curclonedhead=NULL; Randomlistnode Curclonednode=NULL; if(Curnode! =NULL) {Curclonedhead= Curclonednode =Curnode.next; Curnode.next=Curclonednode.next; Curnode=Curnode.next; } while(Curnode! =NULL) {Curclonednode.next=Curnode.next; Curclonednode=Curclonednode.next; Curnode.next=Curclonednode.next; Curnode=Curnode.next; } returnCurclonedhead; } }
Replication of complex lists