142. Linked List Cycle II!
/**
* 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) {
// 1. check if there is a circle (slow and fast pointer)
// 2. get the intersection: two pointer start from head and intersection
ListNode startA = checkCycle(head);
if(startA == null) return null;
ListNode startB = head;
while (startA!=startB){
startA=startA.next;
startB=startB.next;
}
return startA;
}
// if there is no cycle, return null
// if there is a cycle, return the ListNode where slow and fast meet
private ListNode checkCycle(ListNode head){
ListNode slow = head;
ListNode fast = head;
// remember && not ||
while(fast!=null && fast.next!=null){
fast = fast.next.next;
slow = slow.next;
if(fast==slow) return slow;
}
return null;
}
}
Last updated
Was this helpful?