382. Linked List Random Node

来源:互联网 发布:新疆人口普查数据 编辑:程序博客网 时间:2024/05/23 22:17
class Solution {private:    ListNode *head;public:    /** @param head The linked list's head.        Note that the head is guaranteed to be not null, so it contains at least one node. */    Solution(ListNode* head) {        srand(time(NULL));        this->head=head;    }    int random(double min,double max)    {        return (int)(min+((max-min+1)*rand()/(RAND_MAX)));    }    /** Returns a random node's value. */    int getRandom() {        int r=head->val;        ListNode *c=head->next;        for(int i=1;c!=NULL;i++)        {            if(random(0,i)==i)r=c->val;            c=c->next;        }        return r;    }};
1 0
原创粉丝点击