File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
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
+ */
You can’t perform that action at this time.
0 commit comments