HTMLify

LeetCode - Linked List Random Node - Python
Views: 7 | Author: abh
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
from random import randint
class Solution:

    def __init__(self, head: Optional[ListNode]):
        self.head = head
        self.len = 1
        head = head
        while head.next:
            self.len += 1
            head = head.next

    def getRandom(self) -> int:
        i = randint(0, self.len-1)
        return self.get(i)

    def get(self, index) -> Optional[int]:
        head = self.head
        while True:
            index -= 1
            if not index:
                break
            if head.next:
                head = head.next
            else:
                break
        return head.val


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

Comments