My Accepted C++ Sol


  • 0
    K
    class Solution {
    private:
        int numofnode;
        ListNode* myhead;
    
    public:
        Solution(ListNode* head) {
            myhead = head;
            ListNode* ptr = head;
            numofnode=0;
            while(ptr!=NULL){
                numofnode++;
                ptr=ptr->next;
            }
        }
    
        int getRandom() {
            ListNode* ptr = myhead;
            int round = rand()%numofnode;
            while(round!=0){
                round--;
                ptr=ptr->next;
            }
            return ptr->val;
        }
    };
    

Log in to reply
 

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