---
# System prepended metadata

title: Leetcode 382. Linked List Random Node
tags: [Leetcode(C++)]

---

# Leetcode 382. Linked List Random Node
###### tags: `Leetcode(C++)`

題目 : https://leetcode.com/problems/linked-list-random-node/

想法 : 先把值抓出來再Ran給它。

時間複雜度 : O(n)。

程式碼 :

```
/**
 * Definition for singly-linked list.
 * 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:
    
    vector<int> v;
    Solution(ListNode* head) {
        while(head){
            v.push_back(head->val);
            head=head->next;
        }
    }
    
    int getRandom() {
        int r=rand()%v.size();
        return v[r];
    }
};

/**
 * Your Solution object will be instantiated and called as such:
 * Solution* obj = new Solution(head);
 * int param_1 = obj->getRandom();
 */
```