每日一题 382. 链表随机节点

382. 链表随机节点

简单

cpp 复制代码
class Solution {
public:
    int  n;
    ListNode* head;
    Solution(ListNode* head) {
        int cnt = 0;
        this->head = head;
        while(head != 0)
        {
            head = head->next;
            ++cnt;
        }
        n =  cnt;
    }
    
    int getRandom() {
        int idx = rand() % n;
        ListNode* h = head;
        while(idx != 0)
        {
            h = h->next;
            idx--;
        }
        return h->val;

    }
};
相关推荐
alphaTao6 小时前
LeetCode 每日一题 2026/2/2-2026/2/8
算法·leetcode
甄心爱学习6 小时前
【leetcode】判断平衡二叉树
python·算法·leetcode
不知名XL6 小时前
day50 单调栈
数据结构·算法·leetcode
@––––––7 小时前
力扣hot100—系列2-多维动态规划
算法·leetcode·动态规划
YuTaoShao8 小时前
【LeetCode 每日一题】1653. 使字符串平衡的最少删除次数——(解法三)DP 空间优化
算法·leetcode·职场和发展
TracyCoder1239 小时前
LeetCode Hot100(26/100)——24. 两两交换链表中的节点
leetcode·链表
望舒51311 小时前
代码随想录day25,回溯算法part4
java·数据结构·算法·leetcode
铉铉这波能秀11 小时前
LeetCode Hot100数据结构背景知识之集合(Set)Python2026新版
数据结构·python·算法·leetcode·哈希算法
参.商.11 小时前
【Day 27】121.买卖股票的最佳时机 122.买卖股票的最佳时机II
leetcode·golang
铉铉这波能秀12 小时前
LeetCode Hot100数据结构背景知识之元组(Tuple)Python2026新版
数据结构·python·算法·leetcode·元组·tuple