【leetcode】Linked List Cycle II
来源:互联网 发布:知乎36经典回复 编辑:程序博客网 时间:2024/06/06 12:53
class Solution {public: ListNode *detectCycle(ListNode *head) { if(head == NULL || head->next == NULL) return NULL; ListNode *fast = head; ListNode *slow = head; while(fast && fast->next){ fast = fast->next->next; slow = slow->next; if(slow == fast) break; } if(fast != slow) return NULL; fast = head; while(fast != slow){ fast = fast->next; slow = slow->next; } return fast; }};
以上是AC代码
还是利用双指针法:fast slow 两指针
这道题的关键是要明白:
如果有环的话: //以下结论的证明可以在网上搜一搜
首先fast和slow两个指针一定会相遇!!
第一次相遇之后,退出循环,记录相遇时的slow指针 然后把fast 指针重新放回链表开头
第二次相遇时,就是环的入口 然后返回入口节点即可。
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
- 上下文无关文法2
- LeetCode 240: Search a 2D Matrix II
- 常用类之Date类
- 排序汇总
- 第三天上课
- 【leetcode】Linked List Cycle II
- HDOJ 1022 Train Problem I(栈)
- 斐波那契数列——矩阵的幂求解
- HDU 5327 Olympiad
- iOS KVC 概述
- ScrollView介绍
- SVN Cleanup failed to process the following paths
- 线程学习中的错误总结
- 河内塔问题程序