首页 > 其他 > 详细

382. 链表随机节点

时间:2020-04-27 14:53:35      阅读:48      评论:0      收藏:0      [点我收藏+]
 1 class Solution 
 2 {
 3 public:
 4     ListNode* nod;
 5     Solution(ListNode* head) 
 6     {
 7         this->nod = head;
 8     }
 9 
10     int getRandom() 
11     {
12         if(nod == NULL) return 0;
13         int res = nod->val;//第一步选中1个数
14         ListNode* cur = nod;
15         
16         int ind = 1; //当前的个数
17         while(cur->next != NULL)
18         {
19             cur = cur->next;
20             if((rand()%(ind + 1)) == ind) res = cur->val;
21             ind ++;
22         }
23         return res;
24     }
25 };

 

382. 链表随机节点

原文:https://www.cnblogs.com/yuhong1103/p/12786358.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!