aboutsummaryrefslogtreecommitdiff
path: root/linked_list_random.cpp
diff options
context:
space:
mode:
authorjack <[email protected]>2024-06-14 13:13:15 -0600
committerjack <[email protected]>2024-06-14 13:13:15 -0600
commitd343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch)
tree96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /linked_list_random.cpp
downloadleetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz
leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip
initial
Diffstat (limited to 'linked_list_random.cpp')
-rw-r--r--linked_list_random.cpp40
1 files changed, 40 insertions, 0 deletions
diff --git a/linked_list_random.cpp b/linked_list_random.cpp
new file mode 100644
index 0000000..ae147c5
--- /dev/null
+++ b/linked_list_random.cpp
@@ -0,0 +1,40 @@
+// 382. Linked List Random Node
+#include "leetcode.h"
+
+/*
+ * given singly linked list, return a random node's value from the linked list.
+ * each node must have the same probability of being chosen. implement
+ * 'Solution' class: f1: initialises object with head of signly linked list
+ * 'head' f2: chooses node randomly from list and returns its value. all nodes
+ * should be equally likely to be chosen
+ */
+
+class Solution {
+public:
+ Solution(ListNode *head) {
+ this->head = head;
+ while (head != NULL) {
+ this->n++;
+ head = head->next;
+ }
+ }
+ int getRandom() {
+ int i = rand() % this->n;
+ ListNode *p = this->head;
+ while (i) {
+ p = p->next;
+ i -= 1;
+ }
+ return p->val;
+ }
+
+private:
+ int n = 0;
+ ListNode *head = NULL;
+};
+
+int main() {
+ ListNode *head;
+ Solution *obj = new Solution(head);
+ int param_1 = obj->getRandom();
+}