[leetcode] 141. Linked List Cycle
来源:互联网 发布:java ee开发方向 编辑:程序博客网 时间:2024/05/16 06:06
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra spact?
这道题让检测链表是否存在回环,难度为Medium。
- 最直观的想法是使用HashTable,每遍历一个节点检测是否已经存在,如果不存在把它存入HashTable,如果存在则存在回环。空间复杂度为O(n),可惜空间复杂度限制为O(1),只能想其他解决办法了。
- 下面介绍一种快慢指针法,这是Floyd老爷子设计的算法(Orz)。用两个指针fast和slow分别从表头开始遍历,slow每次遍历一个节点,fast每次遍历两个节点,如果fast遍历到表尾(NULL)则没有回环,否则fast和slow必定在回环上某个节点相遇,而且slow还没有走完整个回环。为什么呢?这里不用公式来解释,公式看起来要复杂很多。fast和slow的相对速度是1,slow进入回环时fast必然已在回环中,此时fast和slow之间的距离小于回环长度L,由于相对速度是1,fast追赶上slow不会超过L次遍历,因此slow还没有走完第一圈,而且fast不会跳过slow,两者必定会相遇,搞定。具体代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: bool hasCycle(ListNode *head) { ListNode *p = head; ListNode *q = head; while(q) { p = p->next; q = q->next; if(!q) return false; else q = q->next; if(p == q) return true; } return false; }};
1 0
- [LeetCode]141.Linked List Cycle
- LeetCode 141. Linked List Cycle
- [Leetcode] 141. Linked List Cycle
- LeetCode 141. Linked List Cycle
- [leetcode] 141.Linked List Cycle
- leetcode 141.Linked List Cycle
- [leetcode] 141. Linked List Cycle
- [LeetCode]141. Linked List Cycle
- 141. Linked List Cycle LeetCode
- [LeetCode]141. Linked List Cycle
- LeetCode 141. Linked List Cycle
- LeetCode *** 141. Linked List Cycle
- [LeetCode]141. Linked List Cycle
- LeetCode 141. Linked List Cycle
- [leetcode]141. Linked List Cycle
- leetcode-141. Linked List Cycle
- 141.[LeetCode]Linked List Cycle
- 【leetcode】141. Linked List Cycle
- 卷积神经网络在自然语言处理的应用
- 关于原生js的一些研究
- 观察者模式
- JS正则表达式分组与引用
- 简单工厂、工厂方法、抽象工厂、策略模式、策略与工厂的区别
- [leetcode] 141. Linked List Cycle
- android adb devices offline的解决办法
- 删除重复记录的SQL语句
- Java 日期转毫秒和毫秒转日期
- 装饰器模式(Decorator)
- linux tar 解压命令总结
- js正则表达式元字符与特殊字符
- 起跑线--还不太晚
- 简单工厂模式