138 Copy List with Random Pointer

1. Question

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list

2. Implementation

/**
 * 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) {
        RandomListNode dummy = new RandomListNode(0);
        RandomListNode p = dummy;
        RandomListNode curNode = head;

        while (curNode != null) {
            p.next = clone(curNode);
            curNode = curNode.next;
            p = p.next;
        }
        return dummy.next;
    }

    public RandomListNode clone(RandomListNode node) {
        RandomListNode newNode = new RandomListNode(node.label);
        if (node.random != null) {
            newNode.random = new RandomListNode(node.random.label);
        }
        return newNode;
    }
}

3. Time & Space Complexity

时间复杂度O(n), 空间复杂度O(1)

Last updated

Was this helpful?