LeetCode 3821
思路:
- 首先计算链表长度
- 根据随机数,便利到指定的位置找到结果
代码
代码块语法遵循标准markdown代码,例如:
public class LeetCode382 {
int size = 0;
ListNode head;
public LeetCode382(ListNode head) {
this.head = head; //令成员变量head等于传入的参数head;如果不使用this关键字,语义将变得模糊
ListNode cur = head;
while(cur != null){
size++;
cur = cur.next;
}
}
/** Returns a random node's value. */
public int getRandom() {
ListNode cur = head;
int ran = (int)(Math.random()*size);
while(ran > 0){
cur = cur.next;
ran--;
}
return cur.val;
}
}