141. Linked List Cycle

  • 描述:

    判断一个单链表中是否存在环



  • 思路:
    设置两个指针(fast, slow),初始值都指向头,slow每次前进一步,fast每次前进二步,如果链表存在环,则fast必定先进入环,而slow后进入环,两个指针必定相遇。(当然,fast先行头到尾部为NULL,则为无环链表)
  • 代码
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:  
 
    def hasCycle(self, head):  
        # write your code here  
        if head is None:  
            return False  
        if head.next is None:  
            return False  
        slow = head.next  
        fast = head.next  
        if fast.next is not None:  
            fast = fast.next  
        while (slow.next is not None) and (fast.next is not None):  
            if slow == fast:  
                return True  
            slow = slow.next  
            fast = fast.next  
            if fast.next != None:  
                fast = fast.next  
        return False