382. Linked List Random Node - cocoder39/coco39_LC GitHub Wiki

382. Linked List Random Node

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.
        """
        res = -1
        count = 0
        cur = self.head
        while cur:
            count += 1
            if random.random() < 1/count:
                res = cur.val
            cur = cur.next
        return res