题目
141. 环形链表
思路
双指针的经典应用,可以设置两个指针,一快一慢,都从
head节点开始,慢指针每次走一步,快指针每次走两步,如果链表存在环,那么快慢指针必定相遇,否则会遍历到链表的尾部,为空。
代码
# 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:
fast = slow = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast == slow:
return True
return False