问题描述:
- Given a linked list, determine if it has a cycle in it.
思路:
-
采用快慢指针法,快指针每次前进两个节点,慢指针每次前进一个节点
-
无环条件:node.next=NULL
-
有环条件:快指针指向的节点=慢指针指向的节点
代码:
# 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 True:
try:
fast=fast.next.next
slow=slow.next
if fast==slow:
return True
except:
return False
结果:
Runtime: 40 ms, faster than 100.00% of Python online submissions for Linked List Cycle.