[LeetCode] 142. Linked List Cycle II
来源:互联网 发布:刷淘宝单软件 编辑:程序博客网 时间:2024/05/07 00:28
思路:
设几个变量:
a: 链表头到循环头的距离
b: 循环头到相遇点的距离
c: 相遇点到循环头的距离
n: 循环次数
第一次快慢两个节点相遇时, 快节点走的距离是 a + (b + c) * n1 + b, 慢节点走的距离是 a + (b + c) * n2, 然后 a + (b + c) * n1 = 2 * (a + (b + c) * n2), 但我们不用关注那些走过的整圈, (b + c)的倍数都直接消掉即可. 所以我们就有a == c. 所以两个节点相遇以后, 我们再用start指针和walker指针一起向前移动, 直到他们相遇, 相遇点就是循环起始点.
可以参考一下这个博客, 写的很好http://www.jianshu.com/p/ce7f035daf74
ListNode *detectCycle(ListNode *head) { if (! head || ! head->next) return NULL; ListNode* walker = head; ListNode* runner = head; ListNode* start = head; while (runner->next && runner->next->next) { walker = walker->next; runner = runner->next->next; if (walker == runner) { while (walker != start) { walker = walker->next; start = start->next; } return start; } } return NULL;}
0 0
- [LeetCode]141. Linked List Cycle【&142. Linked List Cycle II】
- leetcode--141. Linked List Cycle&&142. Linked List Cycle II
- LeetCode 141. Linked List Cycle && 142. Linked List Cycle II
- 142. Linked List Cycle II leetcode list
- LeetCode 142. Linked List Cycle II
- [LeetCode]142.Linked List Cycle II
- [leetcode] 142.Linked List Cycle II
- [leetcode] 142. Linked List Cycle II
- leetcode 142. Linked List Cycle II
- [Leetcode]142. Linked List Cycle II @python
- [LeetCode]142. Linked List Cycle II
- 142. Linked List Cycle II LeetCode
- LeetCode:142. Linked List Cycle II
- LeetCode--142. Linked List Cycle II
- LeetCode 142. Linked List Cycle II
- LeetCode 142. Linked List Cycle II
- LeetCode *** 142. Linked List Cycle II
- LeetCode 142. Linked List Cycle II
- 深入研究java.lang.Process类
- Emacs+Cedet+Ecb折腾日记
- 第一行代码读书笔记___4章
- 在windows下安装mysql5.6版本
- Django模板之条件判断和 for 循环
- [LeetCode] 142. Linked List Cycle II
- 常用的20个正则表达式
- linux驱动学习---设备模型别人的理解(1)
- 第十九讲:纯虚函数与抽象类
- cloudstack:ssvm故障处理2--agent状态不正确
- Parajumpers Sale that the spot of
- SQL2008 sa 登录失败解决方法
- 开发笔记1
- android 搜索时关键字变色