Python [Leetcode 141]Linked List Cycle

时间:2023-03-10 07:14:57
Python [Leetcode 141]Linked List Cycle

题目描述:

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

解题思路:

快的指针和慢的指针

代码如下:

# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
slow = fast = head while slow and fast and fast.next:
slow = slow.next
fast = fast.next.next if slow == fast:
return True return False