給定一個鏈表,判斷鏈表中是否有環。
爲了表示給定鏈表中的環,我們使用整數 pos 來表示鏈表尾連接到鏈表中的位置(索引從 0 開始)。 如果 pos 是 -1,則在該鏈表中沒有環。
示例 1:
輸入:head = [3,2,0,-4], pos = 1
輸出:true
解釋:鏈表中有一個環,其尾部連接到第二個節點。
示例 2:
輸入:head = [1,2], pos = 0
輸出:true
解釋:鏈表中有一個環,其尾部連接到第一個節點。
示例 3:
輸入:head = [1], pos = -1
輸出:false
解釋:鏈表中沒有環。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/linked-list-cycle
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
public class Solution {
public boolean hasCycle(ListNode head) {
// return hasCircleI(head);
return hasCircleII(head);
}
//方法二:雙指針
//定義快慢指針,快指針移動2步,慢指針移動1步
//如果鏈表有環,快慢指針會相遇
private boolean hasCircleII(ListNode head) {
if (head == null || head.next == null) return false;
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
return true;
}
}
return false;
}
//方法一:
//暴力法:遍歷鏈表,使用hash/set記錄所有訪問的節點
private boolean hasCircleI(ListNode head) {
Set<ListNode> set = new LinkedHashSet<>();
while (head != null) {
if (set.contains(head)) {
return true;
}
set.add(head);
head = head.next;
}
return false;
}
}