A clean java solution, O(n)


  • 0
    Y
    public RandomListNode copyRandomList(RandomListNode head) {
    	if (head == null) {
    		return null;
    	}
    	RandomListNode newHead = new RandomListNode(head.label);
    	RandomListNode dummy = newHead;
    	while (head != null) {
    		newHead.next = head.next == null ? null : new RandomListNode(head.next.label);
    		newHead.random = head.random == null ? null : new RandomListNode(head.random.label);
    		head = head.next;
    		newHead = newHead.next;
    	}
    	return dummy;
    }

Log in to reply
 

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