题目要求:
Given a linked list, determine if it has a cycle in it.
解题思路:
- 快慢指针 : fast指针一个循环走两步,slow指针一个循环走一步。
-
示意图
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def hasCycle(self, head):
meet = None
fast = head
slow = head
while fast:
fast = fast.next
slow = slow.next
if fast:
fast = fast.next
if fast == slow:
meet = fast
break
if meet == None:
return False
else:
return True
if __name__ == "__main__":
head, head.next, head.next.next = ListNode(1), ListNode(2), ListNode(3)
head.next.next.next, head.next.next.next.next = ListNode(3), ListNode(4)
head.next.next.next.next.next, head.next.next.next.next.next.next = ListNode(4), ListNode(5)
head.next.next.next.next.next.next.next = head.next.next
print(Solution().hasCycle(head))
网友评论