December_day_2

Leetcode December Challenge Day 2 Link to heading

Link to the question

Solution to the question

import random
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
        self.length = None

    def getRandom(self) -> int:
        """
        Returns a random node's value.
        """
        head = self.head
        if self.length == None:
            self.length = 0
            while head != None:
                self.length += 1
                head = head.next
        ind = random.randint(1, self.length)
        head = self.head
        while ind > 0:
            ind -= 1
            if ind == 0:
                return head.val
            head = head.next