-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathlinked-list-random-node.py
More file actions
43 lines (29 loc) · 877 Bytes
/
linked-list-random-node.py
File metadata and controls
43 lines (29 loc) · 877 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import random
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def __init__(self, head: ListNode):
"""
@param head The linked list's head.
Note that the head is guaranteed to be not null, so it contains at least one node.
"""
self._head = head
def getRandom(self) -> int:
"""
Returns a random node's value.
"""
length = 0
node = self._head
selected = -1
while node:
length += 1
if random.randint(1, length) == 1:
selected = node.val
node = node.next
return selected
# Your Solution object will be instantiated and called as such:
# obj = Solution(head)
# param_1 = obj.getRandom()