Leetcode 141题 Linked List Cycle
题目大意: 给出一个链表,判断链表是否循环。循环则返回True,不循环则返回False。
快慢指针法。 一个快指针,一个慢指针。一直跑下去,如果有相等,就说明有循环。 可以想象两个人在操场上绕圈跑步,一个跑得快,一个跑得慢,一直跑下去肯定有一个节点相遇。
思路清晰,代码很容易。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
2020/03/16
英国,疫情隔离。
加油!