JAVA SOLUTION WITH TIME O(N)


  • 0
    E
    /**
     * 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) {
            // sanity check
            if (head == null) {
                return null;
            }
            RandomListNode result = new RandomListNode(0);
            RandomListNode cur = result;
            Map<RandomListNode, RandomListNode> map = new HashMap<>();
            while (head != null) {
                if (!map.containsKey(head)) {
                    map.put(head, new RandomListNode(head.label));
                }
                cur.next = map.get(head);
                
                if (head.random != null) {
                    if (!map.containsKey(head.random)) {
                        map.put(head.random, new RandomListNode(head.random.label));
                    }
                    cur.next.random = map.get(head.random);
                }
                head = head.next;
                cur = cur.next; 
            }
            return result.next;
        }
    }
    

Log in to reply
 

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