C++_56ms_Accepted


  • 0

    #code block

    class Solution {
    
    ListNode* root;
    
    public:
    /* @param head The linked list's head.
    
     Note that the head is guaranteed to be not null, so it contains at least one node. */
    
    Solution(ListNode* head) {
        root = head;
    }
    
    /** Returns a random node's value. */
    int getRandom() {
        int n = 0;
        ListNode* tmp = root; 
        while (tmp) { tmp = tmp->next; n++; }
        int j = rand()%n;
        tmp = root;
        while (j > 0) {tmp = tmp->next;j--;}
        return tmp->val;
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.