Easy to understand Java solution


  • 0
    D
    public class LinkedListRandomNode {
    
        ArrayList<ListNode> list = new ArrayList<>();
    
        /**
         * @param head The linked list's head.
         *             Note that the head is guaranteed to be not null, so it contains at least one node.
         */
        public LinkedListRandomNode(ListNode head) {
            ListNode temp = head;
            while (temp != null) {
                list.add(temp);
                temp = temp.next;
            }
        }
    
        /**
         * Returns a random node's value.
         */
        public int getRandom() {
            int index = new Random().nextInt(list.size());
            return list.get(index).val;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.