# Definition for singly-linked list.# class ListNode:# def __init__(self, val=0, next=None):# self.val = val# self.next = nextclassSolution:def__init__(self,head:Optional[ListNode]):self.head=headdefgetRandom(self)->int:n=ans=0head=self.headwhilehead:n+=1x=random.randint(1,n)ifn==x:ans=head.valhead=head.nextreturnans# Your Solution object will be instantiated and called as such:# obj = Solution(head)# param_1 = obj.getRandom()
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */typeSolutionstruct{head*ListNode}funcConstructor(head*ListNode)Solution{returnSolution{head}}func(this*Solution)GetRandom()int{n,ans:=0,0fornode:=this.head;node!=nil;node=node.Next{n++x:=1+rand.Intn(n)ifn==x{ans=node.Val}}returnans}/** * Your Solution object will be instantiated and called as such: * obj := Constructor(head); * param_1 := obj.GetRandom(); */