[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)。相关文章推荐
- lintcode-102-带环链表
- lintcode 带环链表(102)
- lintcode-带环链表-102
- lintcode(102)带环链表
- LintCode_103_带环链表 II
- [LintCode 451] 两两交换链表中的节点(Python)
- LintCode 带环链表
- [LintCode 96] 链表划分(Python)
- [LintCode 98] 链表排序(Python)
- [LintCode 104] 合并k个排序链表(Python)
- python数据结构之链表——带环链表及交叉链表(双指针法)
- python_lintcode_167链表求和
- 带环链表-LintCode
- lintcode--带环链表II
- LintCode(103)带环链表 II
- python_lintcode_737. Find Elements in Matrix_451. 两两交换链表中的节点
- LintCode 带环链表(快慢指针法)
- lintcode-103-带环链表 II
- python_lintcode_96. 链表划分_389. 判断数独是否合法
- python_lintcode_93. 平衡二叉树_165. 合并两个排序链表_453. 将二叉树拆成链表