法1:快慢指針法:
//給你一個鏈表的頭節點 head ,判斷鏈表中是否有環。
//
// 如果鏈表中有某個節點,可以通過連續跟蹤 next 指針再次到達,則鏈表中存在環。 為了表示給定鏈表中的環,評測系統內部使用整數 pos 來表示鏈表尾連接到
//鏈表中的位置(索引從 0 開始)。注意:pos 不作為參數進行傳遞 。僅僅是為了標識鏈表的實際情況。
//
// 如果鏈表中存在環 ,則返回 true 。 否則,返回 false 。
//
//
//
// 示例 1:
//
//
//
//
//輸入:head = [3,2,0,-4], pos = 1
//輸出:true
//解釋:鏈表中有一個環,其尾部連接到第二個節點。
//
//
// 示例 2:
//
//
//
//
//輸入:head = [1,2], pos = 0
//輸出:true
//解釋:鏈表中有一個環,其尾部連接到第一個節點。
//
//
// 示例 3:
//
//
//
//
//輸入:head = [1], pos = -1
//輸出:false
//解釋:鏈表中沒有環。
//
//
//
//
// 提示:
//
//
// 鏈表中節點的數目范圍是 [0, 10?]
// -10? <= Node.val <= 10?
// pos 為 -1 或者鏈表中的一個 有效索引 。
//
//
//
//
// 進階:你能用 O(1)(即,常量)內存解決此問題嗎?
//
// Related Topics 哈希表 鏈表 雙指針 👍 2114 👎 0//leetcode submit region begin(Prohibit modification and deletion)import java.util.HashSet;/*** 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 || head.next == null) {return false;}ListNode slow = head;ListNode fast = head.next;while (fast != null && fast.next != null) {if (fast == slow) {return true;}slow = slow.next;fast = fast.next.next;}return false;
//這樣寫也行,剛好打了個顛倒
/* while (slow != fast) {if (fast == null || fast.next == null) {return false;}slow = slow.next;fast = fast.next.next;}return true;*/}
}
//leetcode submit region end(Prohibit modification and deletion)
法2:hash法:
public class Solution {public boolean hasCycle(ListNode head) {HashSet<ListNode> hashSet = new HashSet<ListNode>();while (true) {if (head == null) {return false;}boolean isSuccess = hashSet.add(head);if (!isSuccess) {return true;}head = head.next;}}
}