**Description**Hints**Submissions**Solutions
Total Accepted: 112637
Total Submissions: 363331
Difficulty: Medium
Contributor: LeetCode
Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Note: Do not modify the linked list.
Follow up:Can you solve it without using extra space?
Hide Tags
Linked List Two Pointers
Hide Similar Problems
(E) Linked List Cycle (M) Find the Duplicate Number
** 解題思路 **
用快慢指針,快指針一次走兩步窘问,慢指針一次走一步宜咒,來先確定是否有cycle。
如果存在cycle故黑,則將fast = head儿咱,再重新 fast =fast.next, slow = slow.next 兩個指針都單步走场晶,找到fast = slow點即可確定cycle起始點。
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
if (head == null || head.next == null) return null;
ListNode slow = head;
ListNode fast = head;
boolean isCycle = false;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast == slow) {
isCycle = true;
break; // don't forget to break the loop
}
}
if (!isCycle) return null;
// find the node while cycle begins
fast = head;
while (fast != slow) {
fast = fast.next;
slow = slow.next;
}
return slow;
}
}