最近刷题遇到快慢指针判断链表是否循环,我的代码为:
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
fast = slow = head
while fast.next and fast:
fast = fast.next.next
slow = slow.next
if fast == slow:
return True
return False
正确代码为:
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
fast = slow = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast == slow:
return True
return False
正当我感觉没什么不同时,突然想到Python与逻辑会先判断前面的,如果前面的不成立,那整个与表达式就不成立。