Face questions thirty-five: complex list of replication

 

Complex linked list, each node has more than a pointer to the next node, there is a pointer pSibling any node in the table.

Methods: The
first step in creating a node 'N, the N' behind each node N is connected to the rear N

void f1(ListNode pHead){
            ListNode pNode =pHead;
            while( pNode !=null) {
                    ListNode pCloned= new ListNode();
                    pCloned.value = pNode.value;
                    pCloned.next= pNode.next;
                    pCloned.pSibling= null;

                    pNode.next=Cloned;
                    pNode=Cloned.next;
            }

    }

Step Two: Set copied out pSibling node

    void f2(ListNode pHead){
        ListNode pNode =pHead;
        while( pNode !=null) {
                ListNode pCloned= pNode;
                
                if( pNode.pSibling != null)
                       pCloned.pSibling= pNode.pSibling.next;                 
                pNode=Cloned.next;
        }

}

The third step: splitting chain, odd bit original chain is connected, even bit is the result of the copy of the list

   ListNode f3(  ListNode pHead){
             ListNode pNode=pHead;
             ListNode pClonedHead= null;
             ListNode pClonedNode =null;           
             //定义头结点
             if(pNode !=null){
                    pClonedHead=pClonedNode=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;                      
             }     
     }

 

Guess you like

Origin www.cnblogs.com/niliuxiaocheng/p/12592380.html