- hashset解法
public class Solution {public boolean hasCycle(ListNode head) {Set<ListNode> seen = new HashSet<ListNode>();while (head != null) {if (!seen.add(head)) { //如果表里不是空的就会返回falsereturn true;}head = head.next;}return false;}
}
- 快慢指针解法
public boolean hasCycle(ListNode head) {if(head==null||head.next==null) return false;ListNode sl = head;ListNode ft = head.next;while(sl!=ft){if(sl==null||ft==null||ft.next==null) return false; //只要有null就不是环形 而且下面会报空指针sl = sl.next;ft = ft.next.next;}return true;}
如果有环 那么快指针一定能追上慢指针