C++实现LeetCode(142.单链表中的环之二)
[LeetCode] 142. Linked List Cycle II 单链表中的环之二
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
Note: Do not modify the linked list.
Example 1:
Input: head = [3,2,0,-4], pos = 1【C++实现LeetCode(142.单链表中的环之二)】
Output: tail connects to node index 1
Explanation: There is a cycle in the linked list, where tail connects to the second node.
文章图片
Example 2:
Input: head = [1,2], pos = 0
Output: tail connects to node index 0
Explanation: There is a cycle in the linked list, where tail connects to the first node.
文章图片
Example 3:
Input: head = [1], pos = -1
Output: no cycle
Explanation: There is no cycle in the linked list.
文章图片
Follow up:
Can you solve it without using extra space?
这个求单链表中的环的起始点是之前那个判断单链表中是否有环的延伸,可参之前那道 Linked List Cycle。这里还是要设快慢指针,不过这次要记录两个指针相遇的位置,当两个指针相遇了后,让其中一个指针从链表头开始,一步两步,一步一步似爪牙,似魔鬼的步伐。。。哈哈,打住打住。。。此时再相遇的位置就是链表中环的起始位置,为啥是这样呢,这里直接贴上热心网友「飞鸟想飞」的解释哈,因为快指针每次走2,慢指针每次走1,快指针走的距离是慢指针的两倍。而快指针又比慢指针多走了一圈。所以 head 到环的起点+环的起点到他们相遇的点的距离 与 环一圈的距离相等。现在重新开始,head 运行到环起点 和 相遇点到环起点 的距离也是相等的,相当于他们同时减掉了 环的起点到他们相遇的点的距离。代码如下:
class Solution {public:ListNode *detectCycle(ListNode *head) {ListNode *slow = head, *fast = head; while (fast && fast->next) {slow = slow->next; fast = fast->next->next; if (slow == fast) break; }if (!fast || !fast->next) return NULL; slow = head; while (slow != fast) {slow = slow->next; fast = fast->next; }return fast; }};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/142
类似题目:
Linked List Cycle
Find the Duplicate Number
参考资料:
https://leetcode.com/problems/linked-list-cycle-ii/
https://leetcode.com/problems/linked-list-cycle-ii/discuss/44793/O(n)-solution-by-using-two-pointers-without-change-anything
到此这篇关于C++实现LeetCode(142.单链表中的环之二)的文章就介绍到这了,更多相关C++实现单链表中的环之二内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
推荐阅读
- 关于QueryWrapper|关于QueryWrapper,实现MybatisPlus多表关联查询方式
- MybatisPlus使用queryWrapper如何实现复杂查询
- python学习之|python学习之 实现QQ自动发送消息
- 孩子不是实现父母欲望的工具——林哈夫
- opencv|opencv C++模板匹配的简单实现
- Node.js中readline模块实现终端输入
- 【Leetcode/Python】001-Two|【Leetcode/Python】001-Two Sum
- java中如何实现重建二叉树
- leetcode|leetcode 92. 反转链表 II
- 人脸识别|【人脸识别系列】| 实现自动化妆