题目:
题解:
class Solution:
def __init__(self, head: Optional[ListNode]):
self.head = head
def getRandom(self) -> int:
node, i, ans = self.head, 1, 0
while node:
if randrange(i) == 0: # 1/i 的概率选中(替换为答案)
ans = node.val
i += 1
node = node.next
return ans