LeetCode | Linked List Cycle II
来源:互联网 发布:西厢记网络展览馆 编辑:程序博客网 时间:2024/06/05 20:46
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?
题目解析:
一开始想着用“判断两个链表是否相交并求出交点”的方法来做:也就是找到了相交的交点以后,然后判断头结点遍历到这个交点前一个时的个数,然后再从这个交点开始统计有多少个个数,然后用大的减去小的,走同样的让他们到“终点”有相同的步数,然后一起走。结果造成了各种bug。
看了网上介绍以后通过数学算法,经过计算以后就很好解决了:
从head到环的起点长度为x,环起点到快慢指针的相交点长度为y,从相交点到环的起点为z。那么就有2(x+y) = x+y+z+y。就有x = z。什么意思呢?也就是找到相交点以后,一个从head开始遍历,一个从相交点开始遍历,当他们相遇的时候,就找到了环的起点。
有了这个思路以后,代码就相当简洁了。
class Solution {public: ListNode *detectCycle(ListNode *head) { if(head == NULL) return head; ListNode *S = head; ListNode *F = head; while(F && F->next){ F = F->next->next; S = S->next; if(F && S == F){ S = head; while(S != F){ S = S->next; F = F->next; } return S; } } return NULL; }};
0 0
- 【LeetCode】 Linked List Cycle II
- Leetcode: Linked List Cycle II
- <Leetcode>Linked List Cycle II
- [LeetCode] Linked List Cycle II
- Leetcode: Linked List Cycle II
- LeetCode:Linked List Cycle II
- Leetcode Linked List Cycle II
- [LeetCode]Linked List Cycle II
- leetcode Linked List Cycle II
- LeetCode | Linked List Cycle II
- Leetcode: Linked List Cycle II
- [LeetCode] - Linked List Cycle II
- Leetcode: Linked List Cycle II
- LeetCode - Linked List Cycle II
- leetcode Linked List Cycle II
- Linked List Cycle II -- LeetCode
- LeetCode Linked List Cycle II
- [LeetCode] Linked List Cycle II
- 开始写些简单的东西
- 项目开发中整理的工具类,希望对大家有用
- 使用View Link Accessor
- Mina框架技术知识介绍
- 字符串映射(ZOJ 1109)
- LeetCode | Linked List Cycle II
- 往hadoop文件系统上传文件的时候报:could only be replicated to 0 nodes, instead of 1
- 单列集合的特点与使用
- Groovy在ADF BC中的常见用法之一
- Strut2复杂对象数据转移
- poj2135--Farm Tour
- android:contact
- 《互联网创业密码》的书评
- linux sed命令详解