1. 程式人生 > >LintCode:M-帶環連結串列

LintCode:M-帶環連結串列

給定一個連結串列,判斷它是否有環。

您在真實的面試中是否遇到過這個題?  Yes 樣例

給出 -21->10->4->5, tail connects to node index 1,返回 true


/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 */ 
public class Solution {
    /**
     * @param head: The first node of linked list.
     * @return: True if it has a cycle, or false
     */
    public boolean hasCycle(ListNode head) {  
        if(head==null)
            return false;
            
        ListNode fast = head;
        ListNode slow = head;
        while(fast.next!=null && fast.next.next!=null){
            fast = fast.next.next;
            slow = slow.next;
            if(fast==slow)
                return true;
        }
        
        return false;
    }
}