My C++ solution


  • 0
    I
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* current;
        ListNode* myhead;
        /** @param head The linked list's head. Note that the head is guanranteed to be not null, so it contains at least one node. */
        Solution(ListNode* head) {
            myhead = head;
            current = head;
        }
        
        /** Returns a random node's value. */
        int getRandom() {
            int random_value = std::rand() % 11;
            int counter = 0;
            for (int i = 0; i < random_value; i ++) {
                if (current == NULL) {
                    current = myhead;
                }
                current = current -> next;
                counter ++;
            }
            if (current == NULL) {
                current = myhead;
            }
            int value = current -> val;
            for (int i = 0; i < 10 - counter; i ++) {
                if (current == NULL) {
                    current = myhead;
                }
                current = current -> next;
            }
            return value;
        }
    };
    
    /**
     * Your Solution object will be instantiated and called as such:
     * Solution obj = new Solution(head);
     * int param_1 = obj.getRandom();
     */
    

Log in to reply
 

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