# c++ easy solution with follow up solution

• ``````class Solution {
private:
ListNode* curr;
int length;
public:
/** @param head The linked list's head. Note that the head is guanranteed to be not null, so it contains at least one node. */
int i = 0;
i++;
}
length = i;
}

/** Returns a random node's value. */
int getRandom() {
int n = rand() % length;
while(n){
if(!curr->next){
n--;
}
while(curr && curr->next && n){
curr = curr->next;
n--;
}
}
return curr->val;
}
};

``````

``````class Solution {
private:
ListNode* curr;
public:
/** @param head The linked list's head. Note that the head is guanranteed to be not null, so it contains at least one node. */
}

/** Returns a random node's value. */
int getRandom() {
int n = rand();
while(n){
if(!curr->next){
n--;
}
while(curr && curr->next && n){
curr = curr->next;
n--;
}
}
return curr->val;
}
};

``````

• Why the follow up solution working? Where is the initialization of n?
Can you explain a little?
Thanks.

• @cityboygary Thank you for noticing me. I add it to getrandom() function.

• Now it gets "Time Limit Exceeded".

• @StefanPochmann Yes, the reason is that rand() could generate a "big" number.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.