jayati

Linked List Random Node

Mar 9th, 2023
245
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.78 KB | None | 0 0
  1. /**
  2.  * Definition for singly-linked list.
  3.  * struct ListNode {
  4.  *     int val;
  5.  *     ListNode *next;
  6.  *     ListNode() : val(0), next(nullptr) {}
  7.  *     ListNode(int x) : val(x), next(nullptr) {}
  8.  *     ListNode(int x, ListNode *next) : val(x), next(next) {}
  9.  * };
  10.  */
  11. class Solution {
  12. public:
  13.     vector<int> ans;
  14.     Solution(ListNode* head) {
  15.        
  16.         ListNode* temp = head;
  17.         while(temp){
  18.             ans.push_back(temp->val);
  19.             temp=temp->next;
  20.         }
  21.        
  22.     }
  23.    
  24.     int getRandom() {
  25.         int n=ans.size();
  26.         int i = rand()%n;
  27.         return ans[i];
  28.        
  29.     }
  30. };
  31.  
  32. /**
  33.  * Your Solution object will be instantiated and called as such:
  34.  * Solution* obj = new Solution(head);
  35.  * int param_1 = obj->getRandom();
  36.  */
Advertisement
Add Comment
Please, Sign In to add comment