fork(1) download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. struct node
  4. {
  5. int data;
  6. node *next;
  7. };
  8. void push(struct node** head, int d)
  9. {
  10. struct node* t = new node();
  11. t->next=NULL;
  12. t->data = d;
  13. t->next = (*head);
  14. (*head) = t;
  15. }
  16. void selectrandom(node *h)
  17. {
  18. if(!h)return;
  19. int ans=h->data;
  20. for(int i=2;h!=NULL;i++)
  21. {
  22. //change result with probability 1/n
  23. int v=rand()%i;
  24. if(v==0)
  25. ans=h->data;
  26. h=h->next;
  27. }
  28. cout<<ans<<"\t";
  29. }
  30. int main()
  31. {
  32. node *f=NULL;
  33. push(&f, 50);
  34. push(&f, 40);
  35. push(&f, 30);
  36. push(&f, 20);
  37. push(&f, 10);
  38. for(int i=0;i<50;i++)
  39. selectrandom(f);
  40. return 0;
  41. }
  42.  
Success #stdin #stdout 0s 3228KB
stdin
Standard input is empty
stdout
40	30	10	20	10	10	20	30	20	50	40	10	30	10	40	30	30	20	30	10	10	50	40	20	20	20	50	10	30	30	30	10	30	30	10	10	10	20	10	20	10	30	20	40	40	10	10	30	20	10