Total Accepted: 10163 Total Submissions: 33266
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?
/**
* 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) return null;
ListNode lo = head;
ListNode hi = head;
while (hi.next != null && hi.next.next != null) {
lo = lo.next;
hi = hi.next.next;
if (lo == hi) {//c
lo = head;
// a:head, b:begin of cycle, o: length of cycle
// ac=ab+bc 2ac=ab+no+bc=c -> ac = no
// ab=b 2ac+ab=ab+no+bc+ac-bc=ab+2no=b
while(lo != hi) {
lo = lo.next;
hi = hi.next;
}
return lo;
}
}
return null;
}
}