C++ 中的链表随机节点

c++server side programmingprogramming

假设我们有一个单链表,我们需要从链表中随机找到一个节点的值。这里每个节点被选中的概率必须相同。例如,如果列表为 [1,2,3],则它可以返回范围为 1、2 和 3 内的随机节点。

为了解决这个问题,我们将按照以下步骤 −

  • 在 getRandom() 方法中,执行以下操作 −

  • ret := -1, len := 1, v := x

  • 当 v 不为 null 时

    • 如果 rand() 能被 len 整除,则 ret := v 的 val

    • 将 len 增加 1

    • v := v 的 next

  • 返回 ret

示例(C++)

让我们看下面的实现,以便更好地理解 −

#include <bits/stdc++.h>
using namespace std;
class ListNode{
   public:
   int val;
   ListNode *next;
   ListNode(int data){
      val = data;
      next = NULL;
   }
};
ListNode *make_list(vector<int> v){
   ListNode *head = new ListNode(v[0]);
   for(int i = 1; i<v.size(); i++){
      ListNode *ptr = head;
      while(ptr->next != NULL){
         ptr = ptr->next;
      }
      ptr->next = new ListNode(v[i]);
   }
   return head;
}
class Solution {
   public:
   ListNode* x;
   Solution(ListNode* head) {
      srand(time(NULL));
      x = head;
   }
   int getRandom() {
      int ret = -1;
      int len = 1;
      ListNode* v = x;
      while(v){
         if(rand() % len == 0){
            ret = v->val;
         }
         len++;
         v = v->next;
      }
      return ret;
   }
};
main(){
   vector<int> v = {1,7,4,9,2,5};
   ListNode *head = make_list(v);
   Solution ob(head);
   cout << (ob.getRandom());
}

输入

Initialize list with [1,7,4,9,2,5]
Call getRandom() to get random nodes

输出

4
9
1

相关文章