給定一個連結清單,判斷它是否有環。
線上評測位址:
領扣題庫官網 樣例 1:輸入: 21->10->4->5, then tail connects to node index 1(value 10).
輸出: true
樣例 2:
輸入: 21->10->4->5->null
輸出: false
題解
快慢指針的經典題。 快指針每次走兩步,慢指針一次走一步。 在慢指針進入環之後,快慢指針之間的距離每次縮小1,是以最終能相遇。
public class Solution {
public Boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
ListNode fast, slow;
fast = head.next;
slow = head;
while (fast != slow) {
if(fast==null || fast.next==null)
return false;
fast = fast.next.next;
slow = slow.next;
}
return true;
}
}
更多題解參考:
九章官網solution