-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinked List Random Node.py
More file actions
53 lines (36 loc) · 1.13 KB
/
Linked List Random Node.py
File metadata and controls
53 lines (36 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# Definition for singly-linked list.
import random
# THIS PROBLEM STATEMENT MAKES NO FUCKING SENSE.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def __init__(self, head: ListNode): #Annotation :ListNode means head has to be of type ListNode
"""
:type head: Optional[ListNode]
"""
self.head = head
def getLinkedListLength(self):
current_node = self.head
list_length = 0
while current_node:
list_length+=1
current_node = current_node.next
return list_length
def getRandom(self):
"""
:rtype: int
"""
list_length = self.getLinkedListLength()
rand = random.randint(0, list_length)
count = 0
current_node = self.head
while current_node:
if count == rand:
return current_node.val
count+=1
current_node = current_node.next
# Your Solution object will be instantiated and called as such:
# obj = Solution(head)
# param_1 = obj.getRandom()