HTMLify
LeetCode - Linked List Random Node - Python
Views: 388 | Author: abh
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | # 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() |