原題
給定一個鏈表壶运,判斷它是否有環(huán)粗恢。
樣例
給出 -21->10->4->5, tail connects to node index 1喳资,返回 true
解題思路
- 快慢指針檀头,都從起點出發(fā), 慢指針一次一步坎怪,快指針一次兩步,如果有環(huán)則一定存在某時刻快慢指針相交
完整代碼
# 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, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False