您的位置:首页 > 其它

[leetcode 141] Linked List Cycle

2017-05-06 17:23 369 查看
我们可以.用两个指针: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 = None

class 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: