A linked list and a random function are provided to design an algorithm that can return a node of the linked list at random. Each node must return the same probability. The restriction is that you can only link a table once and cannot use extra space.

Source: Internet
Author: User

Interview Questions for a world-renowned Search Engine Company.

To be honest, this type of question is hard to solve if you do not know it. The possible way to think is: (assume there are n nodes in total, n is unknown) when I go to the x node, the information that can be used is that I have already taken step X. You need to decide whether to select the node or not, and the probability of the node being selected is 1/N.

 

The solution is to determine whether to select step X based on the probability of 1/X when the step X is reached. In step x + 1, the probability of step 1/(x + 1) determines whether to select step x + 1. In this way, the probability that the X is treated as the final result is that the X is selected, and the x + 1, x + 2 ,..., n) are not selected. The probability is 1/x * x/(x + 1) * (x + 1)/(x + 2)... (n-1)/n = 1/N.

ExampleCodeAs follows (input error check is not considered ):

Node * getrandomnode (node * Header)

{

Node * P = header;

Node * result = nil;

Int COUNT = 0;

For (; P! = NULL; P = p-> next)

{

Count ++;

If (0 = random (count ))

{

Result = P;

}

P = p-> next;

}

Return result;

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.