(2)寻找链表中环的位置
2015-09-02 14:40
295 查看
算法(1)中,我们已经知道如何判断一个链表中是否有环了,那么怎么找到环的位置呢?
英文命题:
Given
a
linked list, return
the
node where the
cycle begins.
If there is no cycle, return
null.
Follow up:Can you solve
it
without
using
extra space?
解析:思路非常简单,但我们找到环后,立刻把“快指针”移动到头节点,然后,对“快指针”每次向后移动一步,当这个“快指针”和“慢指针”再次相等时,返回指针就好了。
代码:
英文命题:
Given
a
linked list, return
the
node where the
cycle begins.
If there is no cycle, return
null.
Follow up:Can you solve
it
without
using
extra space?
解析:思路非常简单,但我们找到环后,立刻把“快指针”移动到头节点,然后,对“快指针”每次向后移动一步,当这个“快指针”和“慢指针”再次相等时,返回指针就好了。
代码:
ListNode *detectCycle(ListNode *head) { if(!head) { return nullptr; } ListNode * slow = head; ListNode * fast = head; while(slow->next && fast->next && fast->next->next) { slow = slow->next; fast = fast->next->next; //如果找到了环,将fast指针重新设置为head,并每次移动一步,当它再次和slow相同时就是环的起点 if(slow == fast) { fast = head; while(slow != fast) { fast = fast->next; } return fast; } } return nullptr; }
相关文章推荐
- [LeetCode 8] String to Integer(atoi)
- 矩阵元素查找
- Ubuntu配置nginx+php
- Linux httpd 配置端口 apache httpd 域名配置
- C++中的头文件和源文件
- 计算机操作系统——博文目录
- 关于ansbile工具的shell、command、script、raw模块的区别和使用场景
- 黑马程序员——Java之Thread类
- Linux有问必答:如何启用Open vSwitch的日志功能以便调试和排障
- 查询ORACLE表空间或者数据文件每次扩展大小
- dojod自定义属性
- webapp开发框架推荐以及优缺点分析【webAPP干货】
- iOS应用间共享数据
- UE3 内容烘焙
- 在myeclipse中java @override 报错处理
- Linux后台传输screen
- 系统数据库开启
- 国内iOS界最大的行动已经开始了。全面开始翻译iOS开发者文档。
- Qt输入法设计(嵌入式)
- 优化数据页面(28)——不打印颜色和底纹