[LintCode 102] 带环链表(Python)
来源:互联网 发布:光纤网络几根线 编辑:程序博客网 时间:2024/06/05 10:21
题目描述
给定一个链表,判断它是否有环。
样例
给出 -21->10->4->5, tail connects to node index 1,返回 true
思路
快慢针。快针每次都两步,慢针每次走一步。如果无环,快针肯定会率先到达队尾,即遇到None。如果有环,快针永远无法遇到None,并且会与慢针相遇。
代码
"""Definition of ListNodeclass 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
复杂度分析
时间复杂度
阅读全文
0 0
- [LintCode 102] 带环链表(Python)
- lintcode-带环链表-102
- lintcode(102)带环链表
- lintcode-带环链表
- lintcode,带环链表
- 带环链表-LintCode
- [Lintcode]带环链表
- lintcode带环链表
- LintCode 带环链表
- LintCode(102) 带环链表
- lintcode 带环链表(102)
- LintCode-带环链表 II
- LintCode: 带环链表 II
- *[Lintcode]带环链表 II
- 带环链表 II-LintCode
- [LintCode]102.带环链表
- lintcode--带环链表II
- LintCode:M-带环链表
- 每日小记2017.9.4
- OPENSTACK超售比例之VCPU
- redis-3.2.8
- mysql数据库恢复
- NSDecimalNumber的用法
- [LintCode 102] 带环链表(Python)
- fork()函数
- py http测试工具
- MyBatis 03
- JVM内存溢出基本思路
- Maven – 环境配置
- appscan使用指南
- 线程的终止stop与线程的中断interrupted
- 死锁