|
| 1 | +// Source : https://leetcode.com/problems/linked-list-random-node/ |
| 2 | +// Author : Hao Chen |
| 3 | +// Date : 2016-08-24 |
| 4 | + |
| 5 | +/*************************************************************************************** |
| 6 | + * |
| 7 | + * Given a singly linked list, return a random node's value from the linked list. Each |
| 8 | + * node must have the same probability of being chosen. |
| 9 | + * |
| 10 | + * Follow up: |
| 11 | + * What if the linked list is extremely large and its length is unknown to you? Could |
| 12 | + * you solve this efficiently without using extra space? |
| 13 | + * |
| 14 | + * Example: |
| 15 | + * |
| 16 | + * // Init a singly linked list [1,2,3]. |
| 17 | + * ListNode head = new ListNode(1); |
| 18 | + * head.next = new ListNode(2); |
| 19 | + * head.next.next = new ListNode(3); |
| 20 | + * Solution solution = new Solution(head); |
| 21 | + * |
| 22 | + * // getRandom() should return either 1, 2, or 3 randomly. Each element should have |
| 23 | + * equal probability of returning. |
| 24 | + * solution.getRandom(); |
| 25 | + ***************************************************************************************/ |
| 26 | + |
| 27 | +/** |
| 28 | + * Definition for singly-linked list. |
| 29 | + * struct ListNode { |
| 30 | + * int val; |
| 31 | + * ListNode *next; |
| 32 | + * ListNode(int x) : val(x), next(NULL) {} |
| 33 | + * }; |
| 34 | + */ |
| 35 | +class Solution { |
| 36 | +public: |
| 37 | + /** @param head The linked list's head. |
| 38 | + Note that the head is guaranteed to be not null, so it contains at least one node. */ |
| 39 | + Solution(ListNode* head) { |
| 40 | + this->head = head; |
| 41 | + this->len = 0; |
| 42 | + for(ListNode*p = head; p!=NULL; p=p->next, len++); |
| 43 | + srand(time(NULL)); |
| 44 | + } |
| 45 | + |
| 46 | + /** Returns a random node's value. */ |
| 47 | + int getRandom() { |
| 48 | + int pos = rand() % len; |
| 49 | + ListNode *p = head; |
| 50 | + for (; pos > 0; pos--, p=p->next); |
| 51 | + return p->val; |
| 52 | + } |
| 53 | + ListNode* head; |
| 54 | + int len; |
| 55 | +}; |
| 56 | + |
| 57 | +/** |
| 58 | + * Your Solution object will be instantiated and called as such: |
| 59 | + * Solution obj = new Solution(head); |
| 60 | + * int param_1 = obj.getRandom(); |
| 61 | + */ |
0 commit comments