easy C++: make the list a loop


  • -1
    Z

    class Solution {
    public:
    /** @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) {
        start  = head;
        ListNode* curNode = head;
     // make the list a loop
        while(curNode->next!=NULL) curNode = curNode->next;
              curNode->next = head;
    }
    
    /** Returns a random node's value. */
    int getRandom() {
        int randN = rand()%107;
        cout << randN << endl;
        ListNode* curNode = start;
        while(randN--){
            curNode = curNode->next;
        }
        start = curNode->next;
        return curNode->val;
    }
    
    private:
     ListNode* start;
    

    };


Log in to reply
 

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