Skip to content

Commit f0d05ee

Browse files
authored
Create linked-list-random-node.cpp
1 parent fd95958 commit f0d05ee

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

C++/linked-list-random-node.cpp

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
/** @param head The linked list's head. Note that the head is guanranteed to be not null, so it contains at least one node. */
7+
Solution(ListNode* head) : head_(head) {
8+
9+
}
10+
11+
/** Returns a random node's value. */
12+
int getRandom() {
13+
auto reservoir = head_->val;
14+
auto n = 1;
15+
for (auto curr = head_->next; curr; curr = curr->next) {
16+
if (rand() % ++n == 0) {
17+
reservoir = curr->val;
18+
}
19+
}
20+
return reservoir;
21+
}
22+
23+
private:
24+
ListNode *head_;
25+
};
26+
27+
/**
28+
* Your Solution object will be instantiated and called as such:
29+
* Solution obj = new Solution(head);
30+
* int param_1 = obj.getRandom();
31+
*/
32+

0 commit comments

Comments
 (0)