Easy C++ Code


  • 0
    D

    /**

    • Definition for singly-linked list.

    • struct ListNode {

    • int val;
      
    • ListNode *next;
      
    • ListNode(int x) : val(x), next(NULL) {}
      
    • };
      /
      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) {
      h = head;
      Len = 1;
      ListNode* node = head->next;
      while( node != NULL )
      {
      node = node->next;
      ++Len;
      }
      }

      /** Returns a random node's value. */
      int getRandom() {
      int n = rand()%Len;
      return getNNextNode(n)->val;
      }

    private:
    int Len;
    ListNode* h;

    ListNode* getNNextNode( int n ){
        ListNode* node = h;
        while( n-- > 0 )
            node = node->next;
            
        return node;
    }
    

    };

    /**

    • 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.