382.linked-list-random-node.go 701 B

1234567891011121314151617181920212223242526272829303132
  1. /**
  2. * Definition for singly-linked list.
  3. * type ListNode struct {
  4. * Val int
  5. * Next *ListNode
  6. * }
  7. */
  8. type Solution struct {
  9. arr []int
  10. n int
  11. }
  12. /** @param head The linked list's head.
  13. Note that the head is guaranteed to be not null, so it contains at least one node. */
  14. func Constructor(head *ListNode) (sol Solution) {
  15. for curr := head; curr != nil; curr = curr.Next {
  16. sol.arr = append(sol.arr, curr.Val)
  17. sol.n++
  18. }
  19. return
  20. }
  21. /** Returns a random node's value. */
  22. func (this *Solution) GetRandom() int {
  23. return this.arr[rand.Intn(this.n)]
  24. }
  25. /**
  26. * Your Solution object will be instantiated and called as such:
  27. * obj := Constructor(head);
  28. * param_1 := obj.GetRandom();
  29. */