
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Linked List Random Node in C++
Suppose we have a singly linked list, we have to find a random node's value from the linked list. Here each node must have the same probability of being chosen. So for example, if the list is [1,2,3], then it can return random node in range 1, 2, and 3.
To solve this, we will follow these steps −
In the getRandom() method, do the following −
ret := -1, len := 1, v := x
while v is not null
if rand() is divisible by len, then ret := val of v
increase len by 1
v := next of v
return ret
Example(C++)
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; class ListNode{ public: int val; ListNode *next; ListNode(int data){ val = data; next = NULL; } }; ListNode *make_list(vector<int> v){ ListNode *head = new ListNode(v[0]); for(int i = 1; i<v.size(); i++){ ListNode *ptr = head; while(ptr->next != NULL){ ptr = ptr->next; } ptr->next = new ListNode(v[i]); } return head; } class Solution { public: ListNode* x; Solution(ListNode* head) { srand(time(NULL)); x = head; } int getRandom() { int ret = -1; int len = 1; ListNode* v = x; while(v){ if(rand() % len == 0){ ret = v->val; } len++; v = v->next; } return ret; } }; main(){ vector<int> v = {1,7,4,9,2,5}; ListNode *head = make_list(v); Solution ob(head); cout << (ob.getRandom()); }
Input
Initialize list with [1,7,4,9,2,5] Call getRandom() to get random nodes
Output
4 9 1
- Related Articles
- Delete Node in a Linked List in Python
- C# program to find node in Linked List
- Find modular node in a linked list in C++
- Finding middlemost node of a linked list in JavaScript
- Delete a node in a Doubly Linked List in C++
- Find the largest node in Doubly linked list in C++
- C# Program to add a node after the given node in a Linked List
- C# Program to add a node before the given node in a Linked List
- JavaScript Program for Inserting a Node in a Linked List
- Remove Every K-th Node Of The Linked List
- Remove First Node of the Linked List using C++
- Remove Last Node of the Linked List using C++
- Correct the Random Pointer in Doubly Linked List in C++
- Create new linked list from two given linked list with greater element at each node in C++ Program
- C Program to reverse each node value in Singly Linked List

Advertisements