給定一個鏈表,判斷鏈表中是否有環。
為了表示給定鏈表中的環,我們使用整數 pos 來表示鏈表尾連接到鏈表中的位置(索引從 0 開始)。 如果 pos 是 -1,則在該鏈表中沒有環。
示例 1:
輸入:head = [3,2,0,-4], pos = 1
輸出:true
解釋:鏈表中有一個環,其尾部連接到第二個節點。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/linked-list-cycle
解題思路:快慢雙指針
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 not head: 14 return head 15 slow = head 16 fast = head 17 while slow and fast: 18 slow = slow.next 19 if fast.next: 20 fast=fast.next.next 21 else: 22 return False 23 if slow == fast: 24 return True 25 return False