Skip to content

Commit cc81dd3

Browse files
Create ll_random_node.cpp
1 parent 2a6521d commit cc81dd3

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

ll_random_node.cpp

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode() : val(0), next(nullptr) {}
7+
* ListNode(int x) : val(x), next(nullptr) {}
8+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
9+
* };
10+
*/
11+
class Solution {
12+
public:
13+
ListNode* firstNode = NULL;
14+
Solution(ListNode* head) {
15+
firstNode = head;
16+
}
17+
18+
int getRandom() {
19+
int res, len = 1;
20+
ListNode* current = firstNode;
21+
22+
while(current) {
23+
if(rand() % len == 0) {
24+
res = current->val;
25+
}
26+
len++;
27+
current = current->next;
28+
}
29+
return res;
30+
}
31+
};
32+
33+
/**
34+
* Your Solution object will be instantiated and called as such:
35+
* Solution* obj = new Solution(head);
36+
* int param_1 = obj->getRandom();
37+
*/

0 commit comments

Comments
 (0)