A short Java one pass solution


  • 0
    C

    It is not a fast solution. I just want to use some new methods in Java8.

    public class Solution {
        public RandomListNode copyRandomList(RandomListNode head) {
            if (head == null ) return null;
            Map<Integer, RandomListNode> map = new HashMap<>();
            RandomListNode dummyHead = new RandomListNode(0);
            RandomListNode tail = dummyHead;
            while (head != null) {
                map.putIfAbsent(head.label, new RandomListNode(head.label));
                RandomListNode node = map.get(head.label);
                if (head.random != null) {
                    map.putIfAbsent(head.random.label, new RandomListNode(head.random.label));
                    node.random = map.get(head.random.label);
                }
                tail.next = node;
                tail = node;
                head = head.next;
            }
            return dummyHead.next;
        }
    }
    

Log in to reply
 

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