给定一个单链表,从链表返回一个随机节点的值。 每个节点必须具有相同的选择概率。 跟进: 如果这个链表非常大,而且它的长度不为人知呢? 你能解决这个问题,而不使用额外的空间?

来源:互联网 发布:linux man help 编辑:程序博客网 时间:2024/06/15 08:52

本题源自leetcode  382;

-------------------------------------------------------------

思考:用一个随机函数,来做选择。

代码:

 ListNode* head;    /** @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) {        this->head = head;    }        /** Returns a random node's value. */    int getRandom() {        int res = head->val;        ListNode* root = head->next;        int i = 2;        while(root){            int j = rand() % i;            if(j == 0)                res = root->val;            root = root->next;            i++;        }        return res;    }


阅读全文
0 0
原创粉丝点击