Java solution, using map


  • 0
    M
    public class Solution {
        public RandomListNode copyRandomList(RandomListNode head) {
            if(head==null) return null;
            Map<Integer, RandomListNode> map = new HashMap<>();
            RandomListNode dummyHead = new RandomListNode(0);
            for(RandomListNode p=head, q=dummyHead; p!=null; p=p.next, q=q.next){
                q.next = new RandomListNode(p.label);
                map.put(q.next.label, q.next);
            }
            for(RandomListNode p=dummyHead.next, q=head; p!=null; p=p.next, q=q.next){
                if(q.random !=null){
                    p.random = map.get(q.random.label);
                }
            }
            return dummyHead.next;
        }
    }
    

Log in to reply
 

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