# 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):
""" tc O(N) sc O(N)
@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.A = []
cur = head
while cur:
self.A.append(cur.val)
cur = cur.next
self.n = len(self.A)
def getRandom(self) -> int:
""" tc O(1) sc O(N)
Returns a random node's value.
"""
idx = random.randint(0,self.n-1)
return self.A[idx]
# Your Solution object will be instantiated and called as such:
# obj = Solution(head)
# param_1 = obj.getRandom()
Follow up: sc O(1) for unknown size N
# 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:
""" tc O(N) sc O(1)
Returns a random node's value.
"""
n,k = 1,1
res = 0
cur = self.head
while cur:
if random.random() < k/n:
res = cur.val
cur = cur.next
n += 1
return res