【题目】
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
【分析】
检查链表内有没有闭环。其他人的思路,两个指针,一个每次跳一个 Node,另一个每次2个 Node,如果存在闭环,最终快指针会追上慢指针,两者相等。如果无闭环,快指针会先到 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