Skip to content

Latest commit

 

History

History
35 lines (27 loc) · 822 Bytes

382.-linked-list-random-node.md

File metadata and controls

35 lines (27 loc) · 822 Bytes

382. Linked List Random Node

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    import random
    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.list = []
        while head:
            self.list.append(head.val)
            head = head.next
        

    def getRandom(self) -> int:
        """
        Returns a random node's value.
        """
        
        return random.choice(self.list)
        


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