[LeetCode] Linked List Cycle II
2023-09-14 09:08:59 时间
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?
解题思路
设链表长度为n,头结点与循环节点之间的长度为k。定义两个指针slow和fast,slow每次走一步,fast每次走两步。当两个指针相遇时,有:
- fast = slow * 2
- fast - slow = (n - k)的倍数
由上述两个式子能够得到slow为(n-k)的倍数
两个指针相遇后,slow指针回到头结点的位置,fast指针保持在相遇的节点。此时它们距离循环节点的距离都为k,然后以步长为1遍历链表,再次相遇点即为循环节点的位置。
实现代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
//Runtime:16 ms
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if (head == NULL)
{
return NULL;
}
ListNode *slow = head;
ListNode *fast = head;
while (fast->next && fast->next->next)
{
slow = slow->next;
fast = fast->next->next;
if (fast == slow)
{
break;
}
}
if (fast->next && fast->next->next)
{
slow = head;
while (slow != fast)
{
slow = slow->next;
fast = fast->next;
}
return slow;
}
return NULL;
}
};
相关文章
- [LeetCode] Reverse Linked List I II - 链表翻转问题
- leetcode 之Reorder List(25)
- leetcode 之Copy List with Random Pointer(23)
- leetcode 之Remove Nth Node From End of List(19)
- leetcode 之Rotate List(18)
- leetcode 之Partition List(16)
- leetcode 之Reverse Linked List II(15)
- Java实现 LeetCode 749 隔离病毒(DFS嵌套)
- Java实现 LeetCode 面试题13. 机器人的运动范围(DFS)
- Java实现 LeetCode 516 最长回文子序列
- Java实现LeetCode #986 - Interval List Intersections
- Java实现 Leetcode 88 合并两个有序数组
- (LeetCode 82)Remove Duplicates from Sorted List II
- (LeetCode 83)Remove Duplicates from Sorted Lists
- [LeetCode] Linked List Cycle
- [LeetCode] Min Stack
- Leetcode 717. 1 比特与 2 比特字符(可以,一次过)
- Leetcode 804. 唯一摩尔斯密码词(可以,一次过)
- [LeetCode] 206. Reverse Linked List ☆(反转链表)
- leetcode dfs Flatten Binary Tree to Linked List
- leetcode Remove Duplicates from Sorted List
- [LeetCode]Linked List Cycle
- leetcode - Reverse Linked List II
- LeetCode之Sort List
- leetcode 19 -- Remove Nth Node From End of List
- leetcode 83. Remove Duplicates from Sorted List
- 【Leetcode刷题Python】103. 二叉树的锯齿形层序遍历
- 【Leetcode刷题Python】从列表list中创建一颗二叉树
- 【LeetCode】15. 三数之和