packagecom.thealgorithms.datastructures.lists;importjava.util.ArrayList;importjava.util.List;importjava.util.Random;publicclassRandomNode{privateList<Integer> list;privateint size;privatestaticRandom rand =newRandom();staticclassListNode{int val;ListNode next;ListNode(int val){this.val = val;}}publicRandomNode(ListNode head){
list =newArrayList<>();ListNode temp = head;// Now using while loop to traverse through the linked list and// go on adding values and increasing the size value by 1while(temp !=null){
list.add(temp.val);
temp = temp.next;
size++;}}publicintgetRandom(){int index = rand.nextInt(size);return list.get(index);}// Driver program to test above functionspublicstaticvoidmain(String[] args){ListNode head =newListNode(15);
head.next =newListNode(25);
head.next.next =newListNode(4);
head.next.next.next =newListNode(1);
head.next.next.next.next =newListNode(78);
head.next.next.next.next.next =newListNode(63);RandomNode list =newRandomNode(head);int randomNum = list.getRandom();System.out.println("Random Node : "+ randomNum);}}