Welcome to LeetCode Discuss.  Please read the FAQ to help yourself making the best use of Discuss.
Ask a Question
Back to Problem

Welcome to LeetCode Discuss.

This is a place to ask questions related to only OJ problems.

Please read the FAQ to help yourself making the best use of Discuss.

what' wrong with following code

0 votes
85 views

what's wrong with following code? only pass 4/11 test case

Input: {1,2,2,2} Output: {1,2,1,1} Expected: {1,2,2,2}

I test it offline, but it is ok.

enter image description here

The main idea is following picture, 1) Create all nodes in copy linked list using next pointers. 3) Store the node and its next pointer mappings of original linked list. 3) Change next pointer of all nodes in original linked list to point to the corresponding node in copy linked list.

Thank!

public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {
       if(head == null){
           return null;
       }
       HashMap<RandomListNode,RandomListNode> map = new HashMap<RandomListNode,RandomListNode>();

       RandomListNode root =new RandomListNode(head.label);
       RandomListNode res = root;
       RandomListNode copy = head;
       root.next =null;
       //create group2
        RandomListNode temp = null;
       while(head.next!=null){
           head =head.next;
           temp =new RandomListNode(head.label);
           temp.next =null;
           root.next = temp;
           root =root.next;
       }

       // map group 1 to group2
       head = copy;
       root = res;
       while(head!=null){
           map.put(head, res);
           head = head.next;
           root = root.next;
       }

       head = copy;
       root = res;
       //copy random pointer
       while(head!=null){
           root.random=map.get(head.random); 
           head = head.next;
           root = root.next;               
       }

       return res;
}

}

asked Jan 15 in Copy List with Random Pointer by luyulaile (120 points)

Please log in or register to answer this question.


...