@Test public void getRandomTest() { ListNode head = new ListNode(1); head.next = new ListNode(2); head.next.next = new ListNode(3); LinkedListRandomNodeSolution l = new LinkedListRandomNodeSolution(head); int count = 1000; while (count > 0) { count--; assertNotEquals(0, l.getRandom()); } }
int getRandom() { ListNode now = head, result = head; for (int i = 1; now != null; i++) { if (random.nextInt(i) == 0) { result = now; } now = now.next; } return result.val; }
LinkedListRandomNodeSolution { int getRandom() { ListNode now = head, result = head; for (int i = 1; now != null; i++) { if (random.nextInt(i) == 0) { result = now; } now = now.next; } return result.val; } }
LinkedListRandomNodeSolution { int getRandom() { ListNode now = head, result = head; for (int i = 1; now != null; i++) { if (random.nextInt(i) == 0) { result = now; } now = now.next; } return result.val; } LinkedListRandomNodeSolution(ListNode head); }
LinkedListRandomNodeSolution { int getRandom() { ListNode now = head, result = head; for (int i = 1; now != null; i++) { if (random.nextInt(i) == 0) { result = now; } now = now.next; } return result.val; } LinkedListRandomNodeSolution(ListNode head);  }
LinkedListRandomNodeSolution { int getRandom() { ListNode now = head, result = head; for (int i = 1; now != null; i++) { if (random.nextInt(i) == 0) { result = now; } now = now.next; } return result.val; } LinkedListRandomNodeSolution(ListNode head);   }