Given a singly linked list, return a random node ' s value from the linked list. Each node must has the same probability of being chosen.
Follow up:
What if the linked list was extremely large and its length is unknown? Could solve this efficiently without using extra space?
Example:
Init a singly linked list [I/b]. ListNode head = new ListNode (1), Head.next = new ListNode (2); head.next.next = new ListNode (3); Solution solution = new solution (head);//Getrandom () should return either 1, 2, or 3 randomly. Each element should has equal probability of returning.solution.getRandom ();
Analysis:
To a linked list, randomly returning a node, the most straightforward way is to count the length of the list, then randomly generate a position based on the length, and then traverse from the beginning to the position. Considering the way he calls it, we'll start by using each of the values in the linked list stored in the vector array to randomly look for the value and no longer iterate through the list! See the code below:
/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * listnode (int x): Val (x), Next (NULL) {} *}; */class Soluti On {public: /** @param head the linked list ' s head. Note that the head was guanranteed to was not null and so it contains at least one node. * /solution (listnode* head) { m_nlen=0; listnode* Move=head; while (Move!=null) { m_nlen++; Result.push_back (move->val); move=move->next; } } /** Returns A random node ' s value. * /int getrandom () { return Result[rand ()%m_nlen]; } Private: int m_nlen; vector<int> result; };/ * * Your Solution Object would be instantiated and called as such: * Solution obj = new solution (head); * int param_1 = Obj.getrandom (); */
Note: This blog post is Ebowtang original and may continue to be updated later in this article. If reproduced, please make sure to copy this article information!
Original address: http://blog.csdn.net/ebowtang/article/details/52187799
Original Author Blog: Http://blog.csdn.net/ebowtang
This blog leetcode key index: http://blog.csdn.net/ebowtang/article/details/50668895
<leetcode oj> 382. Linked List Random Node