Skip to content

Commit f76cfd3

Browse files
committed
Linked List Cycle/ Linked List Cycle II
1 parent f21cc92 commit f76cfd3

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

141 Linked List Cycle.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
'''
2+
Given a linked list, determine if it has a cycle in it.
3+
4+
Follow up:
5+
Can you solve it without using extra space?
6+
'''
7+
8+
# Definition for singly-linked list.
9+
class ListNode(object):
10+
def __init__(self, x):
11+
self.val = x
12+
self.next = None
13+
14+
15+
class Solution(object):
16+
def hasCycle(self, head):
17+
"""
18+
:type head: ListNode
19+
:rtype: bool
20+
"""
21+
slow = fast = head
22+
while fast and fast.next:
23+
slow = slow.next
24+
fast = fast.next.next
25+
if slow == fast:
26+
return True
27+
return False
28+
29+
30+
if __name__ == "__main__":
31+
None

142 Linked List Cycle II.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
'''
2+
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
3+
4+
Note: Do not modify the linked list.
5+
6+
Follow up:
7+
Can you solve it without using extra space?
8+
'''
9+
10+
# Definition for singly-linked list.
11+
class ListNode(object):
12+
def __init__(self, x):
13+
self.val = x
14+
self.next = None
15+
16+
17+
class Solution(object):
18+
def detectCycle(self, head):
19+
"""
20+
:type head: ListNode
21+
:rtype: ListNode
22+
"""
23+
slow = fast = head
24+
while fast and fast.next:
25+
slow = slow.next
26+
fast = fast.next.next
27+
if slow == fast:
28+
node = head
29+
while node != slow:
30+
node = node.next
31+
slow = slow.next
32+
return node
33+
return None
34+
35+
36+
if __name__ == "__main__":
37+
None

0 commit comments

Comments
 (0)