141. 环形链表

141. 环形链表

方法一

 

# 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
        """
        
        if not head: return False

        first = head  # 快指针
        second = head  # 慢指针
        # 如果列表不存在环,最终快指针先到达尾部,False
        # 如果列表中存在环,快指针最终一定会追上慢指针
        while 1:
            if first.next is None or first.next.next is None:
                return False
            first = first.next.next
            second = second.next
            if first == second:
                return True

 

posted @ 2019-01-18 11:08  小学弟-  阅读(139)  评论(0编辑  收藏  举报