leetcode Linked List Cycle II
来源:互联网 发布:sim卡网络注册失败 编辑:程序博客网 时间:2024/05/16 16:20
问题:Given a linked list, return the node where the cycle begins. If there is no cycle, return null
解决:快慢指针,判断是否有环,然后找进入环的节点
假设在Z点相遇,则快指针走了a+b+c+b,慢指针走了a+b,又因为快指针走了慢指针的两倍,所以2(a+b)=a+b+c+b,推出a=c,所以相遇之后让一个指针从z点出发,另外一个指针从X点出发,每次走一步,相遇的点就是Y点,代码如下
struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution {public: ListNode *detectCycle(ListNode *head) { ListNode *fastp = head, *slowp = head; while(1){ if(fastp == NULL ||fastp->next == NULL) return NULL; fastp = fastp->next->next; slowp = slowp->next; if(slowp == fastp) break; } slowp = head; while(slowp != fastp){ slowp = slowp->next; fastp = fastp->next; } return slowp; }};
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
- 和地方刚回家十分规范化的法国和
- Java遍历文件夹的2种方法
- Delphi 获取时间的年月日
- 图片热点 <MAP>
- vmware下虚拟机centos 桥接上网
- leetcode Linked List Cycle II
- struts2.2 Annotation 注解配置Action
- JDBC批处理
- eclipse配置文件preference导出
- Coder-Strike 2014 - Finals (online edition, Div. 1)-a-b-c
- 国内从事CV相关的企业
- 网页顶端或底部固定层
- Hadoop —— HDFS 和 MapReduce
- 第一篇博文,希望自己能坚持下去