# [leetcode] 382. Linked List Random Node 解题报告

Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen.

What if the linked list is extremely large and its length is unknown to you? Could you solve this efficiently without using extra space?

Example:

// Init a singly linked list [1,2,3].

// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.
solution.getRandom();

/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/** @param head The linked list's head. Note that the head is guanranteed to be not null, so it contains at least one node. */
}

/** Returns a random node's value. */
int getRandom() {
ListNode *tem = p;
int val = p->val;
for(int i =1; tem; i++)
{
if(rand()%i==0) val = tem->val;
tem = tem->next;
}
return val;
}
private:
ListNode *p;
};

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

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120