why my code could be accepted? When I copy the random node, I just create a new one, but if the random point to the former one???


  • 0
    Y

    /**

    • Definition for singly-linked list with a random pointer.
    • class RandomListNode {
    • int label;
      
    • RandomListNode next, random;
      
    • RandomListNode(int x) { this.label = x; }
      
    • };
      */
      public class Solution {
      public RandomListNode copyRandomList(RandomListNode head) {
      if(head == null) return null;
        RandomListNode dummy = new RandomListNode(0);
        RandomListNode head2 = dummy;
      
       
        while(head != null){
            RandomListNode newNode = new RandomListNode(head.label);
            head2.next = newNode;
           
            if(head.random != null){
                newNode.random = new RandomListNode(head.random.label);
            }
        
            head = head.next;
            head2 = head2.next;
        }
        return dummy.next;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.