# 382. Linked List Random Node

<https://leetcode.com/problems/linked-list-random-node/description/>

## solution

```python
# 直接思路：将链表转化为数组，然后通过数组下标实现O(1)的随机取
# Reservoir Sampling思路: 当链表长度未知且只能用常数空间，采用蓄水池算法. (很适合链表无法一次性取到全部, 类似stream)

class Solution(object):
    def __init__(self, head):
        self.head = head

    def getRandom(self):
        count = 0
        res = None

        cur = self.head
        while cur:
            if random.randint(0, count) == 0:
                res = cur.val
            count += 1
            cur = cur.next

        return res
```

时间复杂度：O(n)\
空间复杂度：O(1)

## follow up

[随机类小结](/mle-interview/01_leetcode/16_math/398.-random-pick-index.md)


---

# Agent Instructions: 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://longxingtan.gitbook.io/mle-interview/01_leetcode/16_math/382.-linked-list-random-node.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.
