"Sword Finger Offer" java implementation (2) 21 ~ 30 update

 

25. The number of 1s in binary

Enter a complex linked list (each node has a node value, and two pointers, one points to the next node, and another special pointer points to any node), and the returned result is the head of the complex linked list after copying. (Note, please do not return the node reference in the parameter in the output result, otherwise the judgment program will directly return empty)

/*
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)
     {
        RandomListNode p=pHead;
        RandomListNode t=pHead;
         while (p!= null ){//将p链中每个节点的next节点都设为新建的q节点,q的next为pHead对应节点的next
             RandomListNode q= new RandomListNode(p.label);
             q.next=p.next;
             p.next=q;
             p=q.next;
         }
         while (t!= null ){//t.next是上面那个新建的q节点,而q的random都是null,此处是将q的random都设为pHead对应节点的random的next
             RandomListNode q=t.next;
             if (t.random!= null )
             q.random=t.random.next;
             t=q.next;
             
         }
         RandomListNode s= new RandomListNode( 0 );
         RandomListNode s1=s;
        while (pHead!= null ){
            RandomListNode q=pHead.next;
            pHead.next=q.next;
            q.next=s.next;
            s.next=q;
            s=s.next;
            pHead=pHead.next;
          
            
        }
         return s1.next;
         
     }
}

  

Guess you like

Origin www.cnblogs.com/sjxbg/p/12749589.html