-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinked_list_random_node.cpp
More file actions
61 lines (55 loc) · 1.31 KB
/
linked_list_random_node.cpp
File metadata and controls
61 lines (55 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
* =====================================================================================
*
* Filename: linked_list_random_node.cpp
*
* Description: 382. Linked List Random Node.
* https://leetcode.com/problems/linked-list-random-node/
*
* Version: 1.0
* Created: 03/10/23 10:12:24
* Revision: none
* Compiler: gcc
*
* Author: xianfeng.zhu@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <cstdlib>
#include <ctime>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
struct ListNode {
int val;
ListNode* next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode* next) : val(x), next(next) {}
};
class Solution {
public:
Solution(ListNode* head) : head_(head), size_(0) {
ListNode* p = head;
while (p != nullptr) {
size_++;
p = p->next;
}
std::srand(std::time(0));
}
int getRandom() {
int num = std::rand() % size_;
ListNode* p = head_;
while (num-- > 0) {
p = p->next;
}
return p->val;
}
private:
ListNode* head_;
int size_;
};
TEST(Solution, getRandom) {
ListNode* head = new ListNode(1);
EXPECT_EQ(Solution(head).getRandom(), 1);
}