【題目】
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
【分析】
檢查鏈表內(nèi)有沒有閉環(huán)窒悔。其他人的思路壕翩,兩個指針傅寡,一個每次跳一個 Node北救,另一個每次2個 Node芜抒,如果存在閉環(huán),最終快指針會追上慢指針宅倒,兩者相等。如果無閉環(huán)蹭劈,快指針會先到 None线召。
【代碼】
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @return a boolean
def hasCycle(self, head):
slow = fast = head
if head == None or head.next == None:
return False
else :
while fast and fast.next :
slow = slow.next
fast = fast.next.next
if fast == slow:
return True
return False