Python [Leetcode 141]Linked List Cycle

题目描述:

Given a linked list, determine if it has a cycle in it.

解题思路:

快的指针和慢的指针

代码如下:

# 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

        while slow and fast and fast.next:
            slow = slow.next
            fast = fast.next.next

            if slow == fast:
                return True

        return False

  

 

posted @ 2016-07-28 00:47  scottwang  阅读(277)  评论(0编辑  收藏  举报