Linked List Cycle I II

Linked List Cycle


Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?


Keep two kinds of pointers: faster pointer and slower pointer and keep fixed interval between them. For example, faster pointer will go one step faster than the slower pointer. If the linked list is a cyclic list, faster pointer will end up in catching up with slower pointer. If the linked list is an acyclic list, faster pointer will reach null in the end.


/**
 * 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) {
        if (head == null)
            return false;
        
        ListNode slower = head;
        ListNode faster = head;
        
        while (faster.next != null && faster.next.next != null) {
            slower = slower.next;
            faster = faster.next.next;
            
            if (slower == faster)
                return true;
        }
        
        return false;
    }
    
}
Linked List Cycle II


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 faster = head;
        ListNode slower = head;
        
        while (faster.next != null && faster.next.next != null) {
            slower = slower.next;
            faster = faster.next.next;
            
            if (slower == faster) {
                slower = head;
                
                while (slower != faster) {
                    slower = slower.next;
                    faster = faster.next;
                }
                
                return slower;
            }
        }
        
        return null;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章