Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?算法
給定一個單鏈表,判斷鏈表是否有環。spa
設置兩個指針(fast, slow),初始值都指向頭,slow每次前進一步,fast每次前進二步,若是鏈表存在環,則fast一定先進入環,而slow後進入環,兩個指針一定相遇.net
結點類指針
class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; } }
算法實現類code
public class Solution { // 設置兩個指針(fast, slow),初始值都指向頭,slow每次前進一步,fast每次前進二步, // 若是鏈表存在環,則fast一定先進入環,而slow後進入環,兩個指針一定相遇。 // (固然,fast先行頭到尾部爲NULL,則爲無環鏈表)程序以下: public boolean hasCycle(ListNode head) { ListNode fast = head; ListNode slow = head; while (fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; if (slow == fast) { break; } } return !(fast == null || fast.next == null); } }