382. Linked List Random Node (Medium) - TengnanYao/daily_leetcode GitHub Wiki

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):

    def __init__(self, head):
        """
        @param head The linked list's head.
        Note that the head is guaranteed to be not null, so it contains at least one node.
        :type head: ListNode
        """
        self.head = head

    def getRandom(self):
        """
        Returns a random node's value.
        :rtype: int
        """
        scope = 1
        result = 0
        cur = self.head
        while cur:
            if random.random() < 1.0 / scope:
                result = cur.val
            cur = cur.next
            scope += 1
        return result


# Your Solution object will be instantiated and called as such:
# obj = Solution(head)
# param_1 = obj.getRandom()