您的位置:首页 > 编程语言 > Python开发

[LintCode 102] 带环链表(Python)

2017-09-04 17:13 337 查看

题目描述

给定一个链表,判断它是否有环。

样例

给出 -21->10->4->5, tail connects to node index 1,返回 true

思路

快慢针。快针每次都两步,慢针每次走一步。如果无环,快针肯定会率先到达队尾,即遇到None。如果有环,快针永远无法遇到None,并且会与慢针相遇。

代码

"""
Definition of ListNode
class ListNode(object):

def __init__(self, val, next=None):
self.val = val
self.next = next
"""

class Solution:
"""
@param head: The first node of the linked list.
@return: True if it has a cycle, or false
"""
def hasCycle(self, head):
# write your code here
if head is None:
return False
f = head
s = head
while f.next is not None and f.next.next is not None:
f = f.next.next
s = s.next
if s == f:
return True
return False


复杂度分析

时间复杂度O(n),空间复杂度O(1)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: