[LeetCode]#141. Linked List Cycle
2 min readMar 22, 2020
Environment: Python 3.7
Key technique: Fast and slow pointer, .next
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the second node.
Example 2:
Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the first node.
Example 3:
Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.
Analysis:
Use fast and slow pointer method to check this problem. If fast pointer (move 2 step) and slow pointer (move 1 step) can meet, we can say it is a cycle.
Solution:
class Solution:
def hasCycle(self, head: ListNode) -> bool:
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast: return True
return False
Submitted result:
Lesson learn:
Python 3.7 . next occur ‘list_iterator’ object has no attribute ‘next’ and we can use .__next__() to solve this issue. However, I still can’t solve the Stopiteration and it need time to fix.
Reference:
https://leetcode.com/problems/linked-list-cycle/discuss/542743/Easy-Python-Solution