LeetCode:Linked List Cycle II
来源:互联网 发布:JavaScript 中的注释 编辑:程序博客网 时间:2024/06/08 15:36
这道题代码难度并不大,主要是在于怎么想两个快慢指针的运动。
假设轨道长是K1,经过m步,慢指针pslow到达轨道的K2位置与pfast相等。所以得到第一个等式K1+K2=m。(1)
此时pfast跑了2m步,即K1+K2+xl=2m。(l指圈长,x指圈数)。
此时把pfast移到head处,步长改为1,经过K1步,刚到到达环开始处,而此时,pslow从K2经过K1步,经过(1)等式,刚好也在环起始处,此时返回pfast就好了。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode *detectCycle(ListNode *head) { if(head==NULL||head->next==NULL)return NULL; ListNode* pfast=head; ListNode* pslow=head;while(pfast!=NULL&&pfast->next!=NULL){pfast=pfast->next->next;pslow=pslow->next;if(pfast==pslow){pfast=head;while(pfast!=pslow){pfast=pfast->next;pslow=pslow->next;} return pfast;}} 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
- 错误(一)
- KFS 0.5发布说明
- drop cache
- 网页变模糊js代码
- iOS开发之工具篇-20个可以帮你简化移动app开发流程的工具
- LeetCode:Linked List Cycle II
- cocos2d-x 2.0+eclipse+winxp配置
- 关于程序员开发效率的悖论
- 话务量计算编程实现(MATLAB)
- KFS分布式文件系统测试报告
- 代码编码批量转换
- 青春励志演讲稿——我的理想
- 操作系统复习笔记二:OS Structures
- LeetCode 之实现题(二)