382. 链表随机节点
rand()就可以了
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: long long length; ListNode* h; Solution(ListNode* head) { long long len = 0; ListNode* p = head; while(p) { len++; p = p->next; } length = len; h = head; } int getRandom() { long long cnt = 0; long long k = rand() % length; ListNode* p = h; while(p && cnt < k) { cnt++; p = p->next; } return p->val; } }; /** * Your Solution object will be instantiated and called as such: * Solution* obj = new Solution(head); * int param_1 = obj->getRandom(); */
自己选择的路,跪着也要走完。朋友们,虽然这个世界日益浮躁起来,只要能够为了当时纯粹的梦想和感动坚持努力下去,不管其它人怎么样,我们也能够保持自己的本色走下去。