> For the complete documentation index, see [llms.txt](https://protegejj.gitbook.io/oj-practices/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://protegejj.gitbook.io/oj-practices/chapter1/linked-list/138-copy-list-with-random-pointer.md).

# 138     Copy List with Random Pointer

## 138. [Copy List with Random Pointer](https://leetcode.com/problems/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

```java
/**
 * 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)
