null
.Follow up:
Can you solve it without using extra space?
---
Solution: Maintain two pointers slow and fast, where slow advances by one node at a time, and fast advances by two nodes at a time. When they meet, reset slow to the head of the list. Then advance both slow and fast by one node at a time until they meet at the beginning of the 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) {
ListNode slow = head;
ListNode fast = head;
do {
if (fast == null || fast.next == null) return null;
fast = fast.next.next;
slow = slow.next;
} while (fast != slow);
slow = head;
while (slow != fast) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
}
No comments:
Post a Comment