19-141. Linked List Cycle

题目描述:

Given a linked list, determine if it has a cycle in it.

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

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.

Follow up:

Can you solve it using O(1) (i.e. constant) memory?

第一种实现方法:

 1 def hasCycle(self, head):
 2     try:
 3         slow = head
 4         fast = head.next
 5         while slow is not fast:
 6             slow = slow.next
 7             fast = fast.next.next
 8         return True
 9     except:
10         return False

第二种实现方法:

 1 class Solution(object):
 2     def hasCycle(self, head):
 3         marker1 = head
 4         marker2 = head
 5         while marker2!=None and marker2.next!=None:
 6             marker1 = marker1.next
 7             marker2 = marker2.next.next
 8             if marker2==marker1:
 9                 return True
10         return False

分析:这道题可以看做是两个人在一个赛道上赛跑,其中一个人跑的快,另外一个人跑的慢。如果这个赛道有环,那么终究有一天,两个人都会进入环中。而在一个环中,只要两个人的速度不同,那么它们终将相遇。

原文地址:https://www.cnblogs.com/tbgatgb/p/10995640.html