-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path005. cycle linked list.py
More file actions
54 lines (36 loc) · 872 Bytes
/
005. cycle linked list.py
File metadata and controls
54 lines (36 loc) · 872 Bytes
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
# generate via gpt
#!/usr/bin/env python
# coding: utf-8
# In[1]:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def hasCycle(head):
if not head or not head.next:
return False
slow = head
fast = head.next
while slow != fast:
if not fast or not fast.next:
return False
slow = slow.next
fast = fast.next.next
return True
# generate a chain
def createLinkedList(nums, pos):
if not nums:
return None
nodes = [ListNode(num) for num in nums]
for i in range(len(nodes) - 1):
nodes[i].next = nodes[i + 1]
if pos != -1:
nodes[-1].next = nodes[pos]
return nodes[0]
# test
head_values = [3, 2, 0, -4]
pos = 1
head = createLinkedList(head_values, pos)
result = hasCycle(head)
print(result)
# In[ ]: