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

# 138. Copy List with Random Pointer

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.

## Solution <a href="#solution" id="solution"></a>

```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) {
        if (head == null) return null;

        RandomListNode runner = head;
        while (runner != null) {
            RandomListNode next = runner.next;
            RandomListNode copy = new RandomListNode(runner.label);
            runner.next = copy;
            copy.next = next;

            runner = next;
        }

        runner = head;
        while (runner != null) {
            RandomListNode copy = runner.next;
               if (runner.random != null) {
                copy.random = runner.random.next;
            }
            runner = copy.next;
        }

        runner = head;
        RandomListNode result = runner.next;
        while (runner != null) {
            RandomListNode copy = runner.next;
            runner.next = copy.next;

            runner = runner.next;
            if (runner == null) {
                break;
            }
            copy.next = runner.next;
        }

        return result;
    }
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://anand-aryan.gitbook.io/leetcode/138.-copy-list-with-random-pointer.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
