Offer to prove safety twenty-five: complex list of replication

Casual working

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)

Thinking

This question is in fact for purposes of the operation in terms of logic is not very complicated, complex chain if we are not, we have two ways to copy, one direct redefine a linked list, the original data is a copy of the list and then a return. Second, we were regenerated for each node behind a linked list node before the same node, the node corresponds to a single replication step, then, out of the copy list pulled out to complete the copy of the list, but here can not use the first method, because for the first method for random node to any node is unknown, we can only front to later, for unknown node is no way to effectively deal with, so we use the second methods. After the completion of the completion point complex node again, and finally pulled out of the can, not thinking it is very difficult, but it is for the operation of the list to master.

Code

public class Solution {
    
    public RandomListNode Clone(RandomListNode head)
    {
        RandomListNode p=head;
        RandomListNode q=head;
        while(p!=null){
            RandomListNode temp=new RandomListNode(p.label);
            temp.next=p.next;
            p.next=temp;
            p=temp.next;
        }
        while(q!=null){
            RandomListNode g=q.next;
            if(q.random!=null)
            g.random=q.random.next;
            else q.random=null;
            q=g.next;
            
        }
        RandomListNode c=new RandomListNode(0);
        RandomListNode s=c;
        while(head!=null){
            RandomListNode w=head.next;
            head.next=w.next;
            w.next=s.next;
            s.next=w;
            s=s.next;
            head=head.next;
            
        }
        return c.next;
    }
}
Published 45 original articles · won praise 28 · views 2518

Guess you like

Origin blog.csdn.net/weixin_44015043/article/details/105368122