class Solution {
public:
Note that the head is guaranteed to be not null, so it contains at least one node. */
ListNode* p;
}

/** Returns a random node's value. */
int getRandom() {
int res = p->val;
ListNode* node = p->next;
int i = 2;
while (node) {
int j = rand() % i;
if (j == 0)//这样写的原理是：若生成的随机数在0~i之间，则j=0时rand()=i,
//若生成的随机数在0~2i之间时，rand()=i或2i时j=0，以此类推，这样就保证了上面说明中随机数小于1/n那条性质
res = node->val;
i++;
node = node->next;
}
return res;
}
};

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

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

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

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

## 【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
• 3335

## LeetCode：382. Linked List Random Node（蓄水池抽样算法C++）

382. Linked List Random NodeGiven a singly linked list, return a random node’s value from the linked...
• BestZem
• 2016年08月23日 16:18
• 663

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

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

## [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...
• TstsUgeg
• 2016年08月10日 16:41
• 822

## leetCode(7):Copy list with random pointer

A linked list is given such that each node contains an additional random pointer which could point t...
• Walker19900515
• 2015年06月18日 08:11
• 638

## 148. Linked List Random Node

Given a singly linked list, return a random node's value from the linked list. Each node must have t...
• u010339647
• 2016年08月20日 10:29
• 307

## LeetCode: Copy List with Random Pointer题解

A linked list is given such that each node contains an additional random pointer which could point t...
• angelof7
• 2014年12月16日 13:35
• 552

## LeetCode || Copy List with Random Pointer

Copy List with Random Pointer Total Accepted: 12730 Total Submissions: 56262 My Submissions A l...