[leetcode 141] Linked List Cycle

来源:互联网 发布:iphone6s怎么下载软件 编辑:程序博客网 时间:2024/06/07 12:47

我们可以.用两个指针:one slow and one fast来解决这个问题,slow走一步,fast走两步,slow与fast相遇的地方是slow第一次到达,fast第二次到达的地方

# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution(object):    def hasCycle(self, head):        """        :type head: ListNode        :rtype: bool        """        slow=fast=head        while fast and fast.next:            slow=slow.next            fast=fast.next.next            if id(slow)==id(fast):                return True        return False


0 0
原创粉丝点击