# leetcode： Reservoir Sampling：Linked List Random Node（382）

Given a singly linked list, return a random node’s value from the linked list. Each node must have the same probability of being chosen.

What if the linked list is extremely large and its length is unknown to you? Could you solve this efficiently without using extra space?

Example:

// Init a singly linked list [1,2,3].
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
Solution solution = new Solution(head);

// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.
solution.getRandom();

class Solution {
ListNode* hd;
public:
/** @param head The linked list's head. Note that the head is guanranteed to be not null, so it contains at least one node. */

/** Returns a random node's value. */
int getRandom() {
ListNode* node = hd;
int cnt = 0, randVal = 0;
while(node) {
if(rand() % (++cnt) == 0)
randVal = node->val;
node = node->next;
}
return randVal;
}
};

/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(head);
* int param_1 = obj.getRandom();
*/  

• 本文已收录于以下专栏：

## [leetcode] 382. Linked List Random Node 解题报告

• qq508618087
• 2016年08月12日 04:45
• 3462

## [编程题] LeetCode上的Reservoir Sampling(蓄水池算法)类型的题目

• 2016年09月18日 22:25
• 1359

## 382. Linked List Random Node (蓄水池抽样，java)

382. Linked List Random Node DescriptionSubmissionsSolutions Total Accepted: 23716Total...
• CriminalCode
• 2017年04月10日 15:27
• 265

## 【Leetcode】Linked List Random Node

• yeqiuzs
• 2016年08月10日 11:09
• 1954

## [382]Linked List Random Node

【题目描述】 Given a singly linked list, return a random node's value from the linked list. Each node...
• 2016年09月03日 13:44
• 71

## [leetcode][382] Linked List Random Node

Given a singly linked list, return a random node's value from the linked list. Each node must have t...
• u013805817
• 2017年01月03日 21:37
• 212

## 【LeetCode】Copy List with Random Pointer 解题报告

A linked list is given such that each node contains an additional random pointer which could point t...
• ljiabin
• 2014年09月04日 17:01
• 3351

## LeetCode 382 Linked List Random Node

Given a singly linked list, return a random node’s value from the linked list. Each node must have t...
• xjpk0
• 2017年07月01日 11:52
• 75

## LeetCode #382: Linked List Random Node

Problem Statement(Problem Link) Given a singly linked list, return a random node’s value from the li...
• junchen1992
• 2016年08月29日 09:06
• 306

## leetcode 382 Linked List Random Node C++

• a2331046
• 2016年08月31日 20:44
• 271

举报原因： 您举报文章：leetcode： Reservoir Sampling：Linked List Random Node（382） 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)