classSolution{public:/** @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. */Solution(ListNode*head):head(head){}/** Returns a random node's value. */intgetRandom(){intans=-1;inti=1;for(ListNode*curr=head;curr;curr=curr->next,++i)if(rand()%i==0)ans=curr->val;returnans;}private:ListNode*head;};
classSolution{/** * @param head The linked list's head. Note that the head is guaranteed to be * not null, so it contains at least one node. */publicSolution(ListNodehead){this.head=head;}/** Returns a random node's value. */publicintgetRandom(){intans=-1;inti=1;for(ListNodecurr=head;curr!=null;curr=curr.next,++i)if(rand.nextInt(i)==i-1)ans=curr.val;returnans;}privateListNodehead;privateRandomrand=newRandom();}