Problem

141. Linked List Cycle

142. Linked List Cycle II

Approach

Floyd’s Tortoise and Hare

Code

  • Problem1
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
        ListNode fast = head, slow = head;
        while(fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
            if(fast == slow){
                return true;
            }
        }
        return false;
    }
}
  • problem2
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    private ListNode existCycle(ListNode head){
        ListNode fast = head, slow = head;
        while(fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
            if(fast == slow){
                return fast;
            }
        }
        return null;
    }
    public ListNode detectCycle(ListNode head) {
        ListNode someNodeInCycle = existCycle(head);
        if(someNodeInCycle == null){
            return null;
        }
        ListNode p = head;
        while(p != someNodeInCycle){
            p = p.next;
            someNodeInCycle = someNodeInCycle.next;
        }
        return p;
    }
}