[LeetCode]题解(python):141-Linked List Cycle

题目来源:

  https://leetcode.com/problems/linked-list-cycle/


题意分析:

  给定一个链表,判断链表是否有环。要求O(1)空间时间复杂度。


题目思路:

  用快慢指针可以解决这个问题。一个指针每次走两步,一个每次走一步,那么有环的等价条件是两个指针有重合。通过快慢指针还可以全环的长度。


代码(python):

 1 # Definition for singly-linked list.
 2 # class ListNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution(object):
 8     def hasCycle(self, head):
 9         """
10         :type head: ListNode
11         :rtype: bool
12         """
13         if head == None or head.next == None:
14             return False
15         slow = fast = head
16         while fast and fast.next:
17             slow = slow.next
18             fast = fast.next.next
19             if slow == fast:
20                 return True
21         return False
View Code
原文地址:https://www.cnblogs.com/chruny/p/5443317.html